11 Nov 2014

Advance level questions framed on inheritance virtual function pure virtual function



Q1.
#include <iostream>
using namespace std;
class Base
{
public:
            void virtual f(const int a)
            {
                        cout << "B::f";
            }
};
class Derived : public Base
{
public:
            void f(int  a)
            {
                        cout << "D::f";
            }
};

int main()
{
            Derived d;
            Base *b = &d;
            b->f(1);
            Base bobject;
            bobject.f(1);
            int a=1;
            d.f(a);

            return 0;
}

Output:
D::fB::fD::fD::fD::fB::fD::fD::f

Explanation: Since both function or exactly same so you can pass all permutation and combination of
value like a variable or 1.function f(const int a) and f(int a) is same so base class function will
be overridden.You can apply overridden rule  and callingwill be using base class pointer pointing
to derived class object. if calling happen with derived object then void virtual f(const int a)
will be hidden in derived class so exact matched function in derived class will be called.
Base class actual object will call base class function.

No comments:

Post a Comment