-
Notifications
You must be signed in to change notification settings - Fork 0
/
constructor_example.cpp
87 lines (72 loc) · 2.01 KB
/
constructor_example.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
author Alessandro Ferrante
* constructor_example.cpp
*/
/*
? Introduction of the costructor and the destructor,
? The constructor acts when the object is created,
? performing specific functions such as attribute initialization;
? the destructor acts when the object is deleted,
? performing specific functions such as freeing a dynamic allocation.
*/
/*
? In this example, costruct and destruct have no concrete use,
? in fact the "init" method is still used for the initialization of attributes
*/
#include<iostream>
using namespace std;
/*
? Rectangle class with attributes and methods,
| intruduction of constractor and destructor.
*/
class Rectangle {
private:
// attributes
float b, h;
public:
// ? constructor
Rectangle();
// ? destructor
~Rectangle();
//methods
void init(float _b, float _h);
float compute_area();
float compute_perimeter();
};
/*
? default constructor,
? in this case it does not perform particular functions
*/
Rectangle::Rectangle(){
cout << "Rect constructor " << endl;
}
/*
? default destructor,
? in this case it does not perform particular functions
*/
Rectangle::~Rectangle(){
cout << "Rect destructor " << endl;
}
// Initializes the attributes
void Rectangle::init(float _b, float _h){
b = _b;
h = _h;
}
// Compute and return the perimeter of the rectangle
float Rectangle::compute_perimeter(){
return (b + h) * 2;
}
// Compute and return the area of the rectangle
float Rectangle::compute_area(){
return b * h;
}
int main(int argc, char ** argv){
Rectangle my_rect_1, my_rect_2;
// Initilize the attributes
my_rect_1.init(3, 10);
my_rect_2.init(20.5, 44);
cout << "Perimeter of rect 1 = " << my_rect_1.compute_perimeter() << endl;
cout << "Area of rect 1 = " << my_rect_1.compute_area() << endl;
cout << "Perimeter of rect 2 = " << my_rect_2.compute_perimeter() << endl;
cout << "Area of rect 2 = " << my_rect_2.compute_area() << endl;
}