Whats in this post?
- Background and Explanation of the code
To copy code: Click “View Source” on the right of this code snippet.
Background and Explanation of the code
In the above program, a class rectangle is specified that contains two private data members a and b and two public member functions defined inside the class.
The private data members a and b cannot directly be accessed from main ( ) because their scope is limited to class.The public member functions setdata ( ) and area ( ) can be directly accessed from main ( ) and hence provide well defined interfaces to access the private data members of the class.
In the main ( ),the statement rectangle r1,r2; creates two objects r1,r2 of class rectangle.
The statement r1.setdata (5,10); calls the public member function setdata ( ) through the object r1 and assigns the values 5 and 10 to data members a and b respectively of object r1.The statement r1.area ( ); calls the public member function area ( ) through object r1 and calculates and display the area of rectangle r1 using the value of data members a and b for object r1.
Similarly,the remaining function calls through object r2 assign values 10 and 20 to data members a and b respectively of rectangle object r2 and using these values of data members, area is calculated and displayed.
Area of Rectangle = 50
Area of Rectangle = 200