Write a program to show that virtual function implements dynamic binding.

Sep 2, 2019

Source code:

//program that shows virtual function

#include <iostream>
using namespace std;

//base class
class Shape{
    public:
        virtual void draw(){
            cout<<"This is base class draw function."<<endl;
        }
};
//child class triangle
class Triangle: public Shape{
    public:
        void draw(){
            cout<<"Triangle is drawn here."<<endl;
        }
};
//child class square
class Square: public Shape{
    public:
        void draw(){
            cout<<"Square is drawn here."<<endl;
        }
};

//child class Rectangle
class Rectangle: public Shape{
    public:
        void draw(){
            cout<<"Rectangle is drawn here."<<endl;
        }
};

int main(){
    //pointer to base class
    Shape *base_ptr;
    Rectangle rec;
    Triangle tri;
    Square sqa;
    //sincle pointer of child is compatible to parent pointer
    base_ptr = &rec;
    base_ptr->draw();

    base_ptr = &tri;
    base_ptr->draw();

    base_ptr = &sqa;
    base_ptr->draw();

    return 0;
}

 

Sample run:

Rectangle is drawn here.
Triangle is drawn here.
Square is drawn here.

 

Related


Tools/Apps





© Nepal Exchange Rates