1
votes

I have a base class which has virtual void function1( ) and that is overridden in derived class. Additionally there is one more virtual function in my derived class as below.

class Base
{
    public:
    virtual void function1()
    {
        cout<<"Base::Virtual function1"<<endl;
    }

};
class Derived1:public Base
{
    public:
    void function1()
    {
        cout<<"Derived1::Function1"<<endl;
    }
    virtual void function2()
    {
        cout<<"Derived1::function2"<<endl;

    }
};
int main()
{       
    Base *bptr = new Derived1();
    Derived1 *dptr = new Derived2();
    bptr->function2(); //compile time error

    return 0;
}

I want to know what happens at compile time which is causing compile time error. I want an answer in an interview point of view. How does Vtable and Vptr behave in this scenario. I know there will be one vptr for Base class and that will be inherited to Derived1 class. What does compiler check at compile time?

2
You don't have a Derived2 classCory Kramer
This is essentially the behavior of any compiled language with static typingcuriousguy

2 Answers

3
votes

In the base class Base you dont have a virtual function2, so if you use "Base" as a type compiler can't find a function2.

Change to:

class Base
{
    public:
    virtual void function1()
    {
        cout<<"Base::Virtual function1"<<endl;
    }

    virtual void function2() = 0;

};

And you can use function2. There is another error since you have no Derived2

1
votes

The compiler does not keep track of the run time type of bptr, and instead always considers it to point to an instance of Base. You have to declare function2 in Base as well for the compiler to acknowledge it. Also, shouldn't function1 in Derived be declared virtual as in the base class?