nestharus
nestharus

Reputation: 317

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

Upvotes: 1

Views: 209

Answers (3)

sth
sth

Reputation: 229603

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.

Upvotes: 3

Edward Strange
Edward Strange

Reputation: 40859

Your functions have different signatures. Look at the type for "toolSource". Your second is not an override of the first, but an overload.

Common mistake that the compiler will almost never warn you about. I don't know of one that does anyway.

BTW, there's no reason to use dynamic cast if you're going to use it on a pointer and not check the result.

Upvotes: 1

Matt Kline
Matt Kline

Reputation: 10487

  1. Make sure the function signatures are the same. toolSource isn't const in DefendPropertyPhysical. If the signatures don't match up, the c++ compiler will not assume that you made a mistake, it will just assume that you're declaring a new overload of that method. C++11's explicit override helps with this.

  2. Make sure DefendProperty::apply is marked as virtual in the header.

Upvotes: 0

Related Questions