Академический Документы
Профессиональный Документы
Культура Документы
Static member functions have a class scope and they do not have access
to the this pointer of the class.
Run Online
Static member function
#include <iostream>
using namespace std;
class Cube {
private:
int side; // normal data member
public:
static int objectCount;// static data member
// Constructor definition
Cube()
{
// Increase every time object is created
objectCount++;
}
// creating a static function that returns static data member
static int getCount() {
return objectCount;
}
};
// Initialize static member of class Box
int Cube::objectCount = 0;
int main(void) {
Cube c1;
// Object Count.
cout << "Total objects: " << Cube::getCount() << endl;
Cube c2;
// Object Count.
cout << "Total objects: " << Cube::getCount() << endl;
return 0;
}
Program Explanation
If you compare the first program and this program, the only difference is
that in this program we have created a static member function named getCount()
which returns the static data member objectCount value.
Since getCount is a static member function, it can access only static data
and can be directly called by using the scope resolution operator (::)