[英]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. 我有一个具有虚拟void function1()的基类,该基类在派生类中被重写。 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.
在这种情况下,Vtable和Vptr的行为如何。 I know there will be one vptr for Base class and that will be inherited to Derived1 class.
我知道将有一个vptr用于基类,并且它将继承给Derived1类。 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
. 在基类
Base
您没有虚拟的function2
,因此,如果您使用“ Base”作为类型编译器,则找不到function2
。
Change to: 改成:
class Base
{
public:
virtual void function1()
{
cout<<"Base::Virtual function1"<<endl;
}
virtual void function2() = 0;
};
And you can use function2. 您可以使用function2。 There is another error since you have no Derived2
由于您没有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. 编译器不跟踪bptr的运行时类型,而是始终认为它指向Base的实例。 You have to declare function2 in Base as well for the compiler to acknowledge it.
您还必须在Base中声明function2,以便编译器进行确认。 Also, shouldn't function1 in Derived be declared virtual as in the base class?
另外,不应该像在基类中那样将Derived中的function1声明为虚拟的吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.