- 2074 Chaitra · 3 marks
Simple program illustrating OOP concept
Short answer
A Rectangle class has private length and breadth, public setData and area methods. In main(), objects r1 and r2 are created, dimensions set, and areas printed. This illustrates class/object, encapsulation, and message passing.
Write a simple program that illustrates the object oriented concept.
The program below defines a class Rectangle (encapsulation: data is private, functions are public), creates objects of it, and calls member functions (message passing).
#include <iostream>
using namespace std;
class Rectangle {
private:
float length, breadth; // data hidden from outside
public:
void setData(float l, float b) { // set values
length = l;
breadth = b;
}
float area() { // behaviour of the object
return length * breadth;
}
};
int main() {
Rectangle r1, r2; // two objects of class Rectangle
r1.setData(5, 3);
r2.setData(10, 4.5);
cout << "Area of r1 = " << r1.area() << endl;
cout << "Area of r2 = " << r2.area() << endl;
return 0;
}
Output
Area of r1 = 15
Area of r2 = 45
OOP concepts shown:
- Class and object -
Rectangleis the class;r1andr2are objects. - Encapsulation and data hiding -
lengthandbreadthare private and reached only throughsetData(). - Message passing -
r1.area()sends a message to objectr1.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Prime number program: procedural and OOP · Object Oriented Programming, chapter 1
- Compare procedural and object oriented programming · Object Oriented Programming, chapter 1
- Transpose of matrix using OOP · Object Oriented Programming, chapter 1
- How OOP differs from POP · Object Oriented Programming, chapter 1
- Exception with argument and specification program · Object Oriented Programming, chapter 10
- Concept of class with example · Object Oriented Programming, chapter 1
- Object oriented system and core concepts · Object Oriented Analysis and Design, chapter 1
- Algorithmic vs object-oriented decomposition · Object Oriented Analysis and Design, chapter 1
- Stored program concept and processing cycle · Microprocessor, chapter 1 · asked 6×
- Is OOP enough in OOAD · Object Oriented Analysis and Design, chapter 1