Runtime Polymorphism Example in C++


This is a C++ program that demonstrates the use of abstract classes and virtual functions. The program defines an abstract class Shape with a pure virtual function draw(), which means that any class that derives from Shape must implement the draw() function.

The program also defines two classes Rectangle and Square that inherit from the Shape class and implement the draw() function. In the main() function, we create an object of the Rectangle class and use it to call the draw() function. We then create an object of the Square class and use it to call the draw() function.

Source Code

#include<iostream>
using namespace std;
class Shape
{
public:
    virtual void draw()=0;  //=0 is pure virtual function
};
class Rectangle:public Shape
{
public :
    void draw()
    {
        cout<<"Draw Rectangle"<<endl;
    }
};
class Square:public Shape
{
public :
    void draw()
    {
        cout<<"Draw Square"<<endl;
    }
};
int main()
{
    Shape *o =new Rectangle();
    o->draw();
    o =new Square();
    o->draw();
    return 0;
}
To download raw file Click Here

Output

Draw RectangleDraw Square

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