Monday, February 18, 2013

Interview question on Virtual Function

Que. Can a methode in base class which is declared as virtual be called  using the base class pointer which is pointing to a derived  class object?
 


#include <iostream>
using namespace std;

class B
{
    public:
        virtual void foo()
        {
            cout << "\n its from B" << endl;
        }
};

class D: public B
{
    public:
         void foo()
        {
            cout << "\n its from D" << endl;
        }
};

int main()
{
    B * b = new D();
    b->B::foo();
    b->foo();   //here parent class access the function of child class
//  b->D::foo();  //error -->'D' is not a base of 'B'
    delete b;
    b = 0;

//    D * d = new B;  //error --> invalid conversion from 'B*' to 'D*'
    return 0;
}


OUTPUT:

See in C# also CLICK HERE

No comments:

Post a Comment