C++ Code Example: Rectangle Class
1 # include < iostream >
2 using namespace std ;
3
4 class Rectangle {
5 private :
6 float length ;
7 float width ;
8
9 public :
10 // Default constructor
11 Rectangle () {
12 length = 1.0;
13 width = 1.0;
14 }
15
16 // Parameterized constructor
17 Rectangle ( float l , float w ) {
18 length = l ;
19 width = w ;
20 }
21
22 // Getter for length
23 float getLength () {
24 return length ;
25 }
26
27 // Setter for length
28 void setLength ( float l ) {
29 length = l ;
30 }
31
32 // Getter for width
33 float getWidth () {
34 return width ;
35 }
36
37 // Setter for width
38 void setWidth ( float w ) {
39 width = w ;
1
40 }
41
42 // Method to calculate the area
43 float area () {
44 return length * width ;
45 }
46
47 // Method to display the dimensions of the rectangle
48 void display () {
49 cout << " Length : " << length << " , Width : " << width
<< endl ;
50 }
51 };
52
53 int main () {
54 // Using the default constructor
55 Rectangle rect1 ;
56 cout << " Rectangle 1 ( with default constructor ) : " <<
endl ;
57 rect1 . display () ;
58 cout << " Area : " << rect1 . area () << endl ;
59
60 // Using the parameterized constructor
61 Rectangle rect2 (5.0 , 3.0) ;
62 cout << " Rectangle 2 ( with parameterized constructor ) : "
<< endl ;
63 rect2 . display () ;
64 cout << " Area : " << rect2 . area () << endl ;
65
66 // Using getters and setters to modify and access
private attributes
67 rect1 . setLength (10.0) ;
68 rect1 . setWidth (4.0) ;
69 cout << " Rectangle 1 after using setters : " << endl ;
70 rect1 . display () ;
71 cout << " Area : " << rect1 . area () << endl ;
72
73 return 0;
74 }