Skip to main content

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 - Rectangle is the class; r1 and r2 are objects.
  • Encapsulation and data hiding - length and breadth are private and reached only through setData().
  • Message passing - r1.area() sends a message to object r1.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 1 questions →