1#include <iostream>
2
3class Entity {
4public:
5 static int x,y;
6 static void Print() {
7 std::cout << x << ", " << y << std::endl;
8 }// sta1tic methods can't access class non-static members
9};
10int Entity:: x;
11int Entity:: y;// variable x and y are just in a name space and we declared them here
12int main() {
13 Entity e;
14 Entity e1;
15 e.x = 5;
16 e.y = 6;
17 e1.x = 10;
18 e1.y = 10;
19 e.Print();//output => 10 because variable x and y being static point to same block of memory
20 e1.Print();//output => 10 because variable x and y being static point to same block of memory
21 Entity::x; //you can also acess static variables and functions like this without creating an instance
22 Entity::Print(); //you can also acess static variables and functions like this without creating an instance
23 std::cin.get();
24}
1#include <iostream>
2
3using namespace std;
4
5class Box {
6 public:
7 static int objectCount;
8
9 // Constructor definition
10 Box(double l = 2.0, double b = 2.0, double h = 2.0) {
11 cout <<"Constructor called." << endl;
12 length = l;
13 breadth = b;
14 height = h;
15
16 // Increase every time object is created
17 objectCount++;
18 }
19 double Volume() {
20 return length * breadth * height;
21 }
22 static int getCount() {
23 return objectCount;
24 }
25
26 private:
27 double length; // Length of a box
28 double breadth; // Breadth of a box
29 double height; // Height of a box
30};
31
32// Initialize static member of class Box
33int Box::objectCount = 0;
34
35int main(void) {
36 // Print total number of objects before creating object.
37 cout << "Inital Stage Count: " << Box::getCount() << endl;
38
39 Box Box1(3.3, 1.2, 1.5); // Declare box1
40 Box Box2(8.5, 6.0, 2.0); // Declare box2
41
42 // Print total number of objects after creating object.
43 cout << "Final Stage Count: " << Box::getCount() << endl;
44
45 return 0;
46}
1#include <iostream>
2
3using namespace std;
4
5class Box {
6 public:
7 static int objectCount;
8
9 // Constructor definition
10 Box(double l = 2.0, double b = 2.0, double h = 2.0) {
11 cout <<"Constructor called." << endl;
12 length = l;
13 breadth = b;
14 height = h;
15
16 // Increase every time object is created
17 objectCount++;
18 }
19 double Volume() {
20 return length * breadth * height;
21 }
22
23 private:
24 double length; // Length of a box
25 double breadth; // Breadth of a box
26 double height; // Height of a box
27};
28
29// Initialize static member of class Box
30int Box::objectCount = 0;
31
32int main(void) {
33 Box Box1(3.3, 1.2, 1.5); // Declare box1
34 Box Box2(8.5, 6.0, 2.0); // Declare box2
35
36 // Print total number of objects.
37 cout << "Total objects: " << Box::objectCount << endl;
38
39 return 0;
40}