In this post, we will write a C++ program to display a message by using a virtual function.

C++ program to display a message by using virtual function


C++ program to display a message by using virtual function.

#include<iostream>
#include<conio.h>

class base
{
    private:
        int data;

    public:
        virtual fun()
        {
            std::cout<<"It is the base class"<<std::endl;
            std::cout<<"virtual function"<<std::endl;
        }
};

class derived:public base
{
    public:
        fun()
        {
            std::cout<<"It is the drived class"<<std::endl;
            std::cout<<"veritual class"<<std::endl;
        }
};

class der:public base
{
    public:
        fun()
        {
            std::cout<<"It is the derived two class"<<std::endl;
            std::cout<<"vertual class";
        }
};

int main()
{
    system("cls");

    base *b;
    derived d;
    der d1;

    b = &d;
    b->fun();
    b = &d1;
    b->fun();

    getch();
    return 0;
}



Output

It is the derived class
Virtual class
It is the drived two class
Virtual class