HOW TO MAKE A VIRTUAL FUNCTION IN C PLUS PLUS?

Hank Greenberg

Total Post:12

Points:84
Posted by  Hank Greenberg
 955  View(s)
Ratings:
Rate this:
Hi Expert,

How to make a virtual function in c++?
Please provide line of code.

Thanks in advance. 
  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: How to make a virtual function in C Plus Plus?

    try this:

    Example of Virtual function:
    class base{
    public:
     int i;
    base(int x){ i=x; }
    virtual void func()
    {
    cout<<"Using bse version of func(): ";
    cout<< i<<'\n';
    }
    };

    class derived1:public base{
    public:
    void func()
    {
    cout<<"Using derived1's version of func(): ";
    cout<<i*i<<'\n';
    }
    };

    class derived2:public base{
    public:
    derived2(int x):base(x){}
    void func()
    {
    cout<<"Using derived2's version of func(): ";
    cout<<i+i<<'\n';
    }
    };


    int main()
    {
    base *p;
    base ob(10);
    derived1 d_ob1(10);
    derived2 d_ob2(10);
    p=&ob;
    p->func();
    p=&d_ob1;
    p->func();
    p=&d_ob2;
    p->func();
    return 0;
    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!