File tree Expand file tree Collapse file tree 1 file changed +88
-0
lines changed
Learn_CPP_Programming_Deep_Dive/Section 11 OOP/Constructors Expand file tree Collapse file tree 1 file changed +88
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+
3
+ using namespace std ;
4
+
5
+ class Rectangle
6
+ {
7
+ private:
8
+ int length;
9
+ int breadth;
10
+
11
+ public:
12
+ /* Accessors go here */
13
+ int getLength ()
14
+ {
15
+ return length;
16
+ }
17
+ int getBreadth ()
18
+ {
19
+ return breadth;
20
+ }
21
+
22
+ /* Mutators go here */
23
+ void setLength (int l)
24
+ {
25
+ if (l<0 )
26
+ {
27
+ length = 0 ;
28
+ }
29
+ else
30
+ {
31
+ length = l;
32
+ }
33
+ }
34
+ void setBreadth (int b)
35
+ {
36
+ if (b<0 )
37
+ {
38
+ breadth = 0 ;
39
+ }
40
+ else
41
+ {
42
+ breadth = b;
43
+ }
44
+ }
45
+
46
+ /* There are 4 types of constructors: 1. Compiler provided 2. no-parameterized 3. parameterized 4. copy constructor */
47
+ Rectangle ()
48
+ {
49
+ /* this is non parameterized constructor */
50
+ length = 0 ;
51
+ breadth = 0 ;
52
+ }
53
+
54
+ Rectangle (int l, int b)
55
+ {
56
+ /* this is a parameterized constructor */
57
+ setLength (l);
58
+ setBreadth (b);
59
+ }
60
+
61
+ Rectangle (Rectangle &r)
62
+ {
63
+ /* this is a copy constructor - i am providing a copy example */
64
+ length = r.length ;
65
+ breadth = r.breadth ;
66
+ }
67
+
68
+ int area ()
69
+ {
70
+ return length * breadth;
71
+ }
72
+
73
+ };
74
+
75
+ int main (void )
76
+ {
77
+ Rectangle r1;
78
+ Rectangle r2 (10 ,20 );
79
+
80
+ Rectangle r3 (r2);
81
+
82
+ cout<<" Area of non-parameterized rectangle is " <<r1.area ()<<endl;
83
+ cout<<" Area of non-parameterized rectangle is " <<r2.area ()<<endl;
84
+ cout<<" Area of non-parameterized rectangle is " <<r3.area ()<<endl;
85
+
86
+ return 0 ;
87
+
88
+ }
You can’t perform that action at this time.
0 commit comments