Static Class Member

class A {
public:
static int pref;
};
int  A::pref;

class B: public A {};

class C: public B {};

int main () {

A::pref = 97;

cout<<“A::pref “<<A::pref<<endl;
cout<<“B::pref “<<B::pref<<endl;
cout<<“C::pref “<<C::pref<<endl;
B ppoly1;
C ppoly2;
ppoly1.pref = 83;

cout<<“A::pref “<<A::pref<<endl;
cout<<“ppoly0.pref “<<ppoly0.pref<<endl;
cout<<“ppoly1.pref “<<ppoly1.pref<<endl;

C::pref = 71;

cout<<“A::pref “<<A::pref<<endl;
cout<<“ppoly0.pref “<<ppoly0.pref<<endl;
cout<<“ppoly1.pref “<<ppoly1.pref<<endl;

return 0;

}

 

Static member is a convenient way to share data between different classes. Once the base class (A) has the public static data (pref). Any class inherits it owns the shared data. The data can be accessed or modified by all the classes, and the value will always be the same.

Advertisements

Leave a comment

Filed under C++

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s