YouTip LogoYouTip

Cpp Static Members

# C++ Static Members of a Class [![Image 4: C++ Classes & Objects](#) C++ Classes & Objects](#) We can use the **static** keyword to define class members as static. When we declare a class member as static, it means that no matter how many objects of the class are created, there is only one copy of the static member. !(#) Static members are shared among all objects of the class. If there are no other initialization statements, all static data will be initialized to zero when the first object is created. We cannot place the initialization of static members inside the class definition, but we can redeclare the static variable outside the class using the scope resolution operator **::** to initialize it, as shown in the following example. The following example helps to better understand the concept of static member data: ## Example #includeusing namespace std; class Box{public: static int objectCount; // Constructor definition Box(double l=2.0, double b=2.0, double h=2.0){cout<<"Constructor called."<<endl; length = l; breadth = b; height = h; // Increment every time an object is created objectCount++; }double Volume(){return length * breadth * height; }private: double length; // Length double breadth; // Breadth double height; // Height}; // Initialize static member of class Box int Box::objectCount = 0; int main(void){Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2// Print total number of objects.
← Cpp OverloadingCpp Classes Objects β†’