Static member variables and functions : static « Class « C++






Static member variables and functions

  
#include <iostream>

using namespace std;

class MyClass
{
public:
    static int s_Total;   

    MyClass(int level = 0);
    static int GetTotal();

private:
    int myLevel;
};

int MyClass::s_Total = 0;

MyClass::MyClass(int level):myLevel(level)
{
    cout << "born!" << endl;
    ++s_Total;
}

int MyClass::GetTotal()
{
    return s_Total;
}

int main()
{
    cout << MyClass::s_Total << "\n\n";

    MyClass myObject1, myObject2, myObject3;

    cout << MyClass::GetTotal() << "\n";

    return 0;
}
  
    
  








Related examples in the same category

1.static functions and ID numbers for objects
2.Using a static data member in a class
3.Static member data.
4.Accessing static members without an object.
5.Accessing static members using non-static member functions.
6.Static member functions.
7.static members in classes
8.Calculate salary using static members.
9.static counter
10.Update static field in member method
11.Reference static method along with class name
12.static field is shared among instances