« Static members in C++ objects

Static members in C++

Some properties belong to class rather than to each object. We mark them as static. Static members belongs at common place for all the objects.

Access static members

1cout << Student::totalStudents << endl;

Scope resolution operator

::

Initialising static members

As static property belongs to class we need to initialize outside of the class. Static members can only be initialized outside the class

1int Student ::totalStudents = -2;

Compiler allows to access static members through static members but its not logically correct

1cout << s1.totalStudents << endl;

Changing value of the static members from any place affects at all the places

1s1.totalStudents = 5;
2Student s2;
3cout << s2.totalStudents << endl;
4cout << s1.totalStudents << endl;
5cout << Student::totalStudents << endl;

Change the value of the static members from constructor

1Student()
2{
3 totalStudents++;
4}
1Student s1, s2, s3, s4, s5, s6;
2cout << Student::totalStudents << endl;

totalStudents value will come out to be 6

We can mark functions as static same as properties

static functions also belongs to class rather than objects

1static int getTotalStudents() { return totalStudents; }

Static functions can only access static members of the class

Static functions don't have access this keyword or this pointer

1static int getTotalStudents() { return totalStudents; }

For full class code to try out the code yourself:

https://github.com/anishakd4/ds/tree/master/cn/oops