static constructor c++ code example
Example 1: static class in C++
#include <iostream>
using namespace std;
class Box {
public:
static int objectCount;
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
objectCount++;
}
double Volume() {
return length * breadth * height;
}
static int getCount() {
return objectCount;
}
private:
double length;
double breadth;
double height;
};
int Box::objectCount = 0;
int main(void) {
cout << "Inital Stage Count: " << Box::getCount() << endl;
Box Box1(3.3, 1.2, 1.5);
Box Box2(8.5, 6.0, 2.0);
cout << "Final Stage Count: " << Box::getCount() << endl;
return 0;
}
Example 2: why constructor can't be static in c++
static variable are those variable declared with static and i will be refer to the common property of all the objects in a java and it is mainly used for memory managment in java. constructor is used to inilialize the objects and it is automatically called at time of object creation.
It is not possible in the constructor because static member variables are not associated with each object of the class. It is shared by all objects. If you initialize the static variable into the constructor then it means that you are trying to associate with a particular instance of class. Since this is not possible, it is not allowed.