Classes Example in C++


This program defines a Rectangle class with length and breadth as its data members and area() and perimeter() as its member functions. In the main() function, an object r of the Rectangle class is created and its length and breadth values are set to 5 and 10 respectively. Then, the area() function is called using the r object to calculate and display the area of the rectangle. Note that the perimeter() function is not used in this program.

Source Code

#include<iostream>
using namespace std;
class Rectangle
{
public :
    int length;
    int breadth;
    int area()
    {
        return length*breadth;
    }
    int perimeter()
    {
        return 2*(length+breadth);
    }
};
int main()
{
    Rectangle r;
    r.length=5;
    r.breadth=10;
    cout<<"Area : "<<r.area();
    return 0;
}
To download raw file Click Here

Output

Area : 50

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples