Static Data Member And Static Member Function
Example of static data member
- Static data members of a class are attributes the class.
- The memory for static data members is common to each object.
#include <iostream>
using namespace std;
class Base {
public:
int x;
static int y; // declaration
};
int Base::y; // definition
int main() {
Base b1, b2;
b1.x = 10;
b1.y = 30; // Base::y
b2.x = 20;
Base::y = 40;
cout << b1.x << " " << b2.x << endl;
cout << b1.y << " " << b2.y << endl;
}
output
10 20
40 40
Example of static member function
- Static member functions can only access static data members.
- Non-static member functions can access static or non-static data memebers
#include <iostream>
using namespace std;
class Base {
public:
int x;
static int y; // declaration
void printXY() {cout << x << " " << y << endl;}
static void printY() {cout << y << endl;}
};
int Base::y; // definition
int main() {
Base b1, b2;
b1.x = 10;
b1.y = 30; // Base::y
b2.x = 20;
Base::y = 40;
b1.printXY();
b1.printY(); // Base::printY()
b2.printXY();
Base::printY();
return 0;
}
output
10 40
40
20 40
40
From
Static Data Member And Static Member Function In C++ - Youtube