Coupon Accepted Successfully!


Constructor and Destructor With Static Members

Every object has its own set of data members. When a member function is invoked, only copy of data member of calling object is available to the function. Sometimes, it is necessary for all the objects to share fields which are common for all the objects. If the member variable is declared as static, only one copy of such member is created for entire class. All objects access the same copy of static variable. The static member variable can be used to count the number of objects declared for a particular class. The following program helps you to count the number of objects declared for a class.


9.27 Write a program to declare a static member variable. Count the number of objects created and destroyed.

Explanation: In this program, the class man has one static data member no. The static data member is initialized to zero. Only one copy of static data member is created and all objects share the same copy of static data member.

In function main(), objects A, B, and C are declared. When objects are declared, constructor is executed and static data member no is increased with one. The constructor also displays the value of no on the screen. The value of static member shows us the number of objects present. When the user presses a key, destructor is executed, which destroys the object. The value of static variable is decreased in the destructor. The value of static member variable shows the number of existing objects.

Test Your Skills Now!
Take a Quiz now
Reviewer Name