All about programming in GNU/LINUX

A simple program illustrating use of virtual functions

#include<iostream>
using namespace std;
class base
{
    public:
    void virtual karthik()//virtual function , which can be re-defined in any of the derived classes
    {
        cout<< “Inside Base , i am in 10th std\n”;
    }
};
class derived1:public base
{
    public:
    void karthik()//redefination of the virtual function
    {
        cout<<“INSIDE DERIVED 1 , I AM IN SECOND PU “;
    }
};
class derived2:public base
{
    public:
    void karthik()//redefination 2
    {
        cout<<“\nINSIDE DERIVED 2 , I AM IN DR.AIT C.S.E”;
    }
};
int main()
{
    base *p,b;
    derived1 d1;
    derived2 d2;
    p=&b;//p is a base class pointer
    p->karthik();//accesing function of base
    p=&d1;
    p->karthik();//accesing function of derived 1
    p=&d2;
    p->karthik();//accesing function of derived 2
    return 0;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s