how to make a c++ class static 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: static in class c++
#include <iostream>
class Entity {
public:
static int x,y;
static void Print() {
std::cout << x << ", " << y << std::endl;
}
};
int Entity:: x;
int Entity:: y;
int main() {
Entity e;
Entity e1;
e.x = 5;
e.y = 6;
e1.x = 10;
e1.y = 10;
e.Print();
e1.Print();
Entity::x;
Entity::Print();
std::cin.get();
}