tanishalfelven
tanishalfelven

Reputation: 1186

C++ Accessing child methods from parent pointers

Ok, I'm from Java and currently trying to figure out this C++ stuff. So I've been doodling around, and I have a basic inheritance going on for a basic RPG game type thing. Here's on outline of hierarchy:

Being (Base object that contains a pointer to a Race)
Race (Base Class)
    -Elf (derived class)
    -Human (derived class)

So in my constructor for Being I have the following code:

        int str,
        intl,
        wis,
        dex,
        HP,
        tHP;
    string name;
    Race *race;
public:
            //Send a reference to an object of a SUBCLASS of Race.
    Being(string name, Race *r) 
            :name(name), race(r){
        str = 10;
        intl = 10;
        wis = 10;
        dex = 10;
        tHP = 15;
        HP = tHP;
        race->applyStats(this);
    }

My problem here arises though when I say race->applyStats(this). Although syntactically this succeeds in calling the applyStats method of Race, I want it to call the one of the subclass. For example, I have a class called Elf, that looks like the following:

    class Elf : public Race{
public:
    Elf() 
        :Race("Elf"){
    }
    void applyStats(Being *being){
        cout << "entered" <<endl;
        being->setStr( being->getStr() - 2 );
        being->setWis( being->getWis() + 2 );
        being->setTHP( being->getTHP() - 2 );
    }
};

And in the main I run this code:

Being b ("Tanis", new Elf());
//Don't worry about printStats(), it just lists the stats as the sample output shows
b.printStats();

Sample Output:

 -Tanis-
 Race Elf
 Strength       10
 Intelligence   10
 Wisdom         10
 Dexterity      10
 Health         15/15

Yeah. So I don't really get it, maybe I'm just too used to Java, but when I say applyStats(this), shouldn't it call the applyStats() of the Elf Class?

Upvotes: 1

Views: 381

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310970

In class Race function applyStats must be declared as virtual. For example

virtual void applyStats( const Being *being) const;

(I changed a little its declaration)

Also do not forget to define the destructor of the base class also as virtual.

You may also define class Race as abstract if you use only objects of derived classes. For example

virtual void applyStats( const Being *being) const = 0;

Upvotes: 3

Related Questions