STATIC Data Members
Static keyword has different meanings when used with different types. We can use static keyword with:- Static Variables : Variables in a function, Variables in a class
- Static Members of Class : Class objects and Functions in a class
A static member is shared by all objects of the class. We can't put it in the class definition but it can be initialized outside the class as done in the following example by redeclaring the static variable, using the scope resolution operator :: to identify which class it belongs to.
What is a Static Function?
A function that is declared static using the ‘static
‘ keyword becomes a static function in C++.
Syntax of the Static Function:
static <return_type> <function_name>(<arguments>){
//code
}
When a function inside a class is declared as static, it can be accessed outside the class using the class name and scope resolution operator (::
), without creating any object.
A static member method has access only to the static members of the class, we can not call any non-static functions inside it.
All objects in the class share the same copy of the static function. It is useful in manipulating global static variables, which are again shared by all objects.
Since the static function is not bounded by the object of the class, it does not has access to the this
keyword.
CODE
KEY-NOTES
- The static data member belongs to the class, not to any particular object.
- For initializing the static data member, we need to change it through class by using the scope resolution operator (iff the data member is public).
- int Student :: totalStudents = 0;
- In static functions, we can use only static data members.
- Other non-static functions can also use static data members.
- We can call static functions within a static function.
- We cannot use this keyword in static member functions.
- We cannot call any static data member through an object.
0 Response to "Static Data Member | OOPS"
Post a Comment
If you have any doubts, please let me know...