Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 431e30a

Browse files
understand 3 types of constructors
1 parent 4cc8ad1 commit 431e30a

File tree

1 file changed

+88
-0
lines changed
  • Learn_CPP_Programming_Deep_Dive/Section 11 OOP/Constructors

1 file changed

+88
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
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+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /