views:

202

answers:

2

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?

+3  A: 
Nikolai N Fetissov
If I'm not mistaken, your last example should be `pp->isAwesome()`.
Chris Lutz
Chris, thanks. Corrected.
Nikolai N Fetissov
The comment on your second example (for `awesomeness1`) is incorrect. Since `rap` is a reference, the call *is* through the vtable, not direct. It is correct that `true` is returned though.
Jon-Eric
A mistake only a Java programmer would make, passing an object by value.
Omnifarious
Jon-Eric, you are right, sort of. The compiler already knows the exact object type, so it *doesn't need* to go through the vtable, and might just generate direct instead of virtual call.
Nikolai N Fetissov
+6  A: 

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.

R Samuel Klatchko
This was the problem, thanks very much for the explanation!
Han