[英]C++ Inherited Virtual Method Still Uses Base Class Implementation
I have a base class called Packet
: 我有一个名为Packet
的基类:
// Header File
class Packet {
public:
virtual bool isAwesome() const {
return false;
}
}
and an inherited class called AwesomePacket
: 和一个名为AwesomePacket
的继承类:
// Header File
class AwesomePacket : public Packet {
public:
virtual bool isAwesome() const {
return true;
}
}
However, when I instantiate an AwesomePacket
and call isAwesome()
, the method returns false
instead of true
. 但是,当我实例化一个AwesomePacket
并调用isAwesome()
,该方法返回false
而不是true
。 Why is this the case? 为什么会这样?
By any chance is your code calling isAwesome in the Packet constructor: 你的代码调用在任何可能性都是在Packet构造函数中是令人敬畏的:
Packet::Packet()
{
// this will always call Packet::isAwesome
if (isAwesome())
{
}
}
Even if this Packet constructor is being used to construct the parent object of an AwesomePacket object, this will not call AwesomePacket::isAwesome. 即使使用此Packet构造函数构造AwesomePacket对象的父对象,也不会调用AwesomePacket :: isAwesome。 This is because at this point in time the object is not yet an AwesomePacket. 这是因为此时对象还不是AwesomePacket。
It all depends on how you call the method. 这一切都取决于你如何调用该方法。 Consider this: 考虑一下:
AwesomePacket ap;
bool awesomeness0( ap.isAwesome()); // true, call is direct, not through vtable
AwesomePacket& rap( ap );
bool awesomeness1( rap.isAwesome()); // true, call is direct, not through vtable
Packet p( ap ); // WRONG (but legal): slicing child instance into space of parent
bool awesomeness2( p.isAwesome()); // false, call is direct, not through vtable
const Packet& rp( ap ); // the right way
bool awesomeness3( rp.isAwesome()); // true, call is through vtable
const Packet* pp( &ap ); // also the right way
bool awesomeness4( pp->isAwesome()); // true, call is through vtable
This is to say that polymorphism in C++ only works via reference or a pointer to base. 这就是说C ++中的多态性只能通过引用或指向base的指针来工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.