Pointer to Classes Example in C++


This program defines a class named Rectangle that has two public member variables length and breadth and two member functions area() and perimeter(). The area() function returns the area of the rectangle and the perimeter() function returns the perimeter of the rectangle.

In the main() function, an instance of the Rectangle class named r is created and its length and breadth values are set to 5 and 10, respectively. Then, the area() function of the r object is called and its return value is printed to the console using the cout statement.

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

Stack Area : 50Heap Area : 100

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