Search code examples
c++virtual

c++ virtual method isn't being called


I have two c++ classes declared in headers. The base declares a virtual method and the second class overrides it. The implementations are in .cpp files.

The code is fairly simple

void DefendProperty::apply(Queue<Defend*>* defendQueue, 
const Tool* toolSource, const Actor* actorSource, const Actor* defender) {
    cout << "BASE" << endl;
}

void DefendPropertyPhysical::apply(Queue<Defend*>* defendQueue, 
Tool* toolSource, const Actor* actorSource, const Actor* defender) {
    cout << "CORRECT" << endl;
    defendQueue->enqueue(new Defend(
        DefendTypePhysical::TYPE, 
        new DamageValuesPhysical(
        getRandomDouble(minDamageReduction, maxDamageReduction))
    ));
}

The point is that when I call the class instantiated as B, it outputs BASE, not CORRECT. I have no idea what's going on at this point.

The classes are stored in a base ToolProperty type that doesn't have the apply method. When they are called, they are typecasted into the DefendProperty type using dynamic_cast.

dynamic_cast<DamageProperty*>(node->value)->apply(damageQueue, toolSource, actorSource);

Any help would be appreciated


Solution

  • The signature of the method in the derived class is different of the one in the base class. (One takes a const Tool*, the other a non-const Tool*)

    Because of the different signature the method of the derived class doesn't override the method of the base class, but instead declares a new, unrelated method.