简体   繁体   中英

Why do I get compile time error when base class pointer points to derived class virtual function that is declared in base class?

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?

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM