开发者

C++ Inherited Virtual Method Still Uses Base Class Implementation

I have a base class called Packet:

// Header File
class Packet开发者_运维问答 {
public:
    virtual bool isAwesome() const {
        return false;
    }
}

and an inherited class called 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. Why is this the case?


By any chance is your code calling isAwesome in the Packet constructor:

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. This is because at this point in time the object is not yet an 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.

Edit:

Don't forget to add a virtual destructor in the base class.

Edit:

It also depends on where you call your virtual method, see the answer by R Samuel Klatchko.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜