-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathb.cpp
69 lines (57 loc) · 1.35 KB
/
b.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
using namespace std;
class Rectangle
{
int height, width;
public:
Rectangle(int h, int w);
Rectangle(int dim);
Rectangle();
int getArea();
~Rectangle();
};
Rectangle::Rectangle(int h, int w)
{
cout << "constructor called.\n";
height = h;
width = w;
}
Rectangle::Rectangle(int dim)
{
cout << "constructor called.\n";
height = width = dim;
}
Rectangle::Rectangle()
{
cout << "constructor called.\n";
height = width = 0;
}
int Rectangle::getArea()
{
return height * width;
}
Rectangle::~Rectangle()
{
cout << "Destructor called\n";
}
int main()
{
Rectangle *rp = nullptr; //no instance is created.
rp = new Rectangle; //default constructor is called.
cout << "Area1:- " << rp->getArea() << "\n";
delete rp;
rp = new Rectangle(3); //initialized by calling constructor.
cout << "Area2:- " << rp->getArea() << "\n";
delete rp;
rp = new Rectangle(3, 4);
cout << "Area3:- " << rp->getArea() << "\n";
delete rp;
rp = new Rectangle[3]; //for dynamically allocated object array, the object must have default constructor.
for (int i = 0; i < 3; i++)
{
//cout << "Area4:- " << rp[i].getArea() << "\n";
cout << "Area4:- " << (rp + i)->getArea() << "\n"; //pointer arithmetic is applicable
}
delete[] rp;
return 0;
}