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:
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 class and can be called without creating any instance of the class. They can access only static data members of the class and cannot access any non-static data members or member functions.
Example:
public:
static int myStaticVar;
static void myStaticFunc() {
cout << "This is a static function." << endl;
cout << "The value of myStaticVar is: " << myStaticVar << endl;
}
};
int MyClass::myStaticVar = 0; // defining the static member outside the class
int main() {
MyClass::myStaticVar = 5; // accessing static member without creating object
MyClass::myStaticFunc(); // calling static function
}
Static data members and static member functions are useful in situations where you need to maintain a single copy of a variable or function for all instances of the class. They can also improve performance by avoiding unnecessary object creation and destruction.
No comments:
Post a Comment
If you have any doubts, please let me know