-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConstructor.cpp
More file actions
65 lines (62 loc) · 1.5 KB
/
Constructor.cpp
File metadata and controls
65 lines (62 loc) · 1.5 KB
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
// Constructor.cpp : Program to demonstrate the use of constructor in C++
#include <iostream>
using namespace std;
class rectangle
{
private:
int length;
int breadth;
public:
rectangle(rectangle& rec) // Copy constructor, it's passed as a reference to another object to copy its properties
{
length = rec.length;
breadth = rec.breadth;
}
rectangle() // Non-parametrized constructor (user-defined)
{
length = 0;
breadth = 0;
}
rectangle(int x, int y) // Parametrized constructor
{
setLength(x);
setBreadth(y);
}
void setLength(int l)
{
if (l < 0)
{
cout << "Length can't be negative.";
}
else
{
length = l;
}
}
void setBreadth(int b)
{
if (b < 0)
{
cout << "Breadth can't be negative.";
}
else
{
breadth = b;
}
}
int area()
{
return length * breadth;
}
int perimeter()
{
return 2 * (length + breadth);
}
};
int main()
{
rectangle r(10, 5); // Parametrized constructor is called here
cout << "Area of rectangle 1 is: " << r.area() << endl;
rectangle r2(r); // r2 object is created which has same properties as r (same values)
cout << "Area of rectangle 2 is: " << r2.area() << endl; // Same area because it has same values
}