Data Hiding Example in C++


This program is an example of using dynamic memory allocation to create an object on the heap. The new keyword is used to allocate memory for a new Rectangle object on the heap, and the address of the newly created object is stored in the pointer variable h.

The program also shows an example of using a pointer to access an object on the stack. The address of the r object is assigned to the pointer variable p, and the -> operator is used to access the member variables and member functions of the object through the pointer.

Overall, this program demonstrates the flexibility of object-oriented programming in C++, where objects can be created on the stack or the heap and accessed through pointers.

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,*p;//Using Stack
    p=&r;
    p->length=5;
    p->breadth=10;
    cout<<"Stack Area : "<<p->area()<<endl;

    Rectangle *h=new Rectangle(); //Using Heap
    h->length=10;
    h->breadth=10;
    cout<<"Heap Area : "<<h->area();
    return 0;
}
To download raw file Click Here

Output

Stack Area : 50
Heap Area : 100Stack Area : 50
Heap 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