fork download
  1. // www.tutorialspoint.com/cplusplus/cpp_static_members.htm
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. class Box {
  7. public:
  8. static int objectCount;
  9.  
  10. // Constructor definition
  11. Box(double l = 2.0, double b = 2.0, double h = 2.0) {
  12. cout <<"Constructor called." << endl;
  13. length = l;
  14. breadth = b;
  15. height = h;
  16.  
  17. // Increase every time object is created
  18. objectCount++;
  19. }
  20. double Volume() {
  21. return length * breadth * height;
  22. }
  23.  
  24. private:
  25. double length; // Length of a box
  26. double breadth; // Breadth of a box
  27. double height; // Height of a box
  28. };
  29.  
  30. // Initialize static member of class Box
  31. int Box::objectCount = 0;
  32.  
  33. int main(void) {
  34. Box Box1(3.3, 1.2, 1.5); // Declare box1
  35. Box Box2(8.5, 6.0, 2.0); // Declare box2
  36.  
  37. // Print total number of objects.
  38. cout << "Total objects: " << Box::objectCount << endl;
  39.  
  40. return 0;
  41. }
Success #stdin #stdout 0.01s 5448KB
stdin
Standard input is empty
stdout
Constructor called.
Constructor called.
Total objects: 2