Skip to main content

Posts

Showing posts with the label static data members

Discuss static data member and static member function with proper illustrations.

 In C++, a static member is a member of a class that belongs to the class itself rather than to any instance of the class. It is shared by all instances of the class and can be accessed without creating any instance of the class. Static data members are declared using the keyword 'static' and must be defined outside the class declaration. Example: class MyClass {   public:     static int myStaticVar; }; int MyClass::myStaticVar = 0; // defining the static member outside the class int main() {   MyClass obj1;   MyClass obj2;      MyClass::myStaticVar = 5; // accessing static member without creating object      obj1.myStaticVar = 3; // this will also change the static variable for obj2      cout << obj1.myStaticVar << endl; // output: 3   cout << obj2.myStaticVar << endl; // output: 3 (since the static member is shared) } Static member functions are also shared by all instances of the c...