Static members A class can contain static members, either data or functions. 




A static member variable has following properties:
1. It is initialized to zero when the first object of its class is created. No other initialization is permitted.
2. Only one copy of that member is created for the entire class and is shared by all the objects of that class.
3. It is the visible only within the class but its lifetime is the entire program.

Static data members of a class are also known as "class variables", because there is only one unique value for all the objects of that same class. Their content is not different from one object static members have the same properties as global variables but they enjoy class scope. For that reason, and to avoid them to be declared several times, we can only include the prototype (its declaration) in the class declaration but not its definition (its initialization). In order to initialize a static data-member, we must include a formal definition outside the class, in the global scope of this class to another. Because it is a unique variable value for all the objects of the same class, it can be referred to as a member of any object of that class or even directly by the class name (of course this is only valid for static members.

A static member function has following properties:
1. A static function can have access to only other static members (fun or var) declared in the same class
2. A static function can be called using the class name instead of its object name

Class_name :: fun_name; 
Static member functions are considered to have class scope. In contrast to non-static member functions, these functions have no implicit this argument; therefore, they can use only static data members, enumerators, or nested types directly. Static member functions can be accessed without using an object of the corresponding class type. The following restrictions apply to such static functions:
1. They cannot access non-static class member data using the member-selection operators (. or –>).
2. They cannot be declared as virtual.
3. They cannot have the same name as a non-static function that has the same argument types.

E.g. // static members in classes 
class StaticTest 
private: 
static int x; 
public: 
static int count() 
return x; 
}; 
int StaticTest::x = 9; 
int main() 



{ printf_s("%d\n", StaticTest::count()); 

Output 9
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: