1

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?

curiousguy
  • 8,038
  • 2
  • 40
  • 58
arjun jawalkar
  • 138
  • 1
  • 10
  • You don't have a `Derived2` class – Cory Kramer Mar 15 '19 at 13:07
  • 1
    Possible duplicate of [Unable to call derived class function using base class pointers](https://stackoverflow.com/questions/17514243/unable-to-call-derived-class-function-using-base-class-pointers) – Kevin Mar 15 '19 at 13:08
  • This is essentially the behavior of any compiled language with static typing – curiousguy Mar 25 '19 at 19:45

2 Answers2

3

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

Enoc Martinez
  • 165
  • 1
  • 4
1

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?

Inon Peled
  • 691
  • 4
  • 11
  • 1
    `function1` in `Derived` *is* virtual, simply because it's virtual in `Base`. The keyword is optional, though for clarity it should probably be there. – Kevin Mar 15 '19 at 13:10