Search code examples
c++inheritancevirtual

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?


Solution

  • 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.