As we Know that For Accessing any thing means Data Members and Member Functions from a Class we must have to Create an Object First, So that When we Creates an Object of Class , then all the Data of Class will be Copied into an Object so that this will Consume Some Memory So that double Memory will be used for Storing the Data of single Class. First, Memory used by Class for storing his data and Second by Object.
So that for Removing the Problem for storing the data and Member Functions twice. We uses the Static and Static Member Functions.
Static Data Members
are those which are declared by using the Static Keyword in front of the Data Members. Means Put the Static Keyword in front of the Variables. And Static Data Members always have Default values as\ 0 for int and Null for Strings. So that they will Never Stores any Garbage values. Always remember that Static Data Members are always used in the Static Member Functions. Means if a Member Functions wants to use a Static Data then we must have to declare that Member Function as Static. And the Static Data Members are always Assigned Some values from the outside from the Class.
Static Member Functions:
The Static Member Functions are those which are declared by using the Static in Front of the Member Function. And in this we use the Static Data Members. Any Method can be converted into the Static just by Using the Static in front of the Member Function.
For Accessing the Static data Member Function we doesn’t need to Create an Object of Class and we will call the Function with the name of Class and Scope resolution Operator. So thatthere will be no object and no Extra Memory is required to Store the Data of a Class.
Let us try the following example to understand the concept of static function members:
#include <iostream> using 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; // Increase every time object is created objectCount++; } double Volume() { return length * breadth * height; } static int getCount() { return objectCount; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; // Initialize static member of class Box int Box::objectCount = 0; int main(void) { // Print total number of objects before creating object. cout << "Inital Stage Count: " << Box::getCount() << endl; 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 after creating object. cout << "Final Stage Count: " << Box::getCount() << endl; return 0; }
When the above code is compiled and executed, it produces the following result:
Inital Stage Count: 0 Constructor called. Constructor called. Final Stage Count: 2