-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path20.cpp
49 lines (42 loc) · 962 Bytes
/
20.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
using namespace std;
class Rectangle
{
static int rectCreated; //static member variable
int height, width;
public:
Rectangle(int h, int w);
static int getRectCreated(); //static member function
~Rectangle();
};
Rectangle::Rectangle(int h, int w)
{
cout << "constructor called.\n";
height = h;
width = w;
rectCreated++;
}
int Rectangle::getRectCreated()
{
return rectCreated;
}
Rectangle::~Rectangle()
{
cout << "Destructor called\n";
rectCreated--;
}
/*
1| has to be defined outside the class to ensure memory allocation.
2| the same static variable will be shared by any class derived from the class that contains the static member
*/
int Rectangle::rectCreated = 0;
int main()
{
cout << Rectangle::getRectCreated() << "\n";
{
Rectangle rect1(1, 2);
cout << rect1.getRectCreated() << "\n";
}
cout << Rectangle::getRectCreated() << "\n";
return 0;
}