1
    class CommandRoot {
protected:
    string cmdString = "";
    string title = "";
    string tags = "";
    string description = "";

public:
    string getCmdString() {
        return cmdString;
    }
    string getTitle() {
        return title;
    }
    string getTags() {
        return tags;
    }
    string getDescription() {
        return description;
    }

    virtual bool onTrigger() {
        return 1;
    }
};

class CmdFirst : public CommandRoot{    
public:
    CmdFirst() {
        cmdString = "testing1";
        title = "";
        tags = "";
        description = "";
    }

    bool onTrigger() {
        cout << "C";
        return 0;
    }
};

class Player {
    NPC *target = NULL;
    CommandRoot *cmdList[1];

public:
    Player() {
        cmdList[0] = new CmdFirst();
    }

    CommandRoot getCmdList(int n) {
        return *cmdList[n];
    }

    NPC getTarget() {
        return *target;
    }

    bool setTarget(NPC* t) {
        target = t;
        return 0;
    }

    string listen() {
        string cmd = "";
        cin >> cmd;
        return cmd;
    }
};

int main()
{
    std::cout << "Hello World!\n";

    Player* player = new Player();
    NPC* firstNPC = new NPC();
    player->setTarget(firstNPC);

    bool exit = false;
    do {
        if (player->listen().compare(player->getCmdList(0).getCmdString()) == 0) {
            cout << "A";
            cout << player->getCmdList(0).onTrigger();
        }
        else
        {
            cout << "B";
        }
    } while (exit == false);
}

The following line is calling the parent's virtual function instead of the derived class.

cout << player->getCmdList(0).onTrigger();

I have a feeling it's because the data type of the array is the parent class, but that shouldn't prevent the array element from being assigned the data type of the derived class, then calling that class's function.

1 Answers1

4

It's because CommandRoot getCmdList(int n) returns a CommandRoot object. For virtual functions to work you need a reference or a pointer.

Try changing to

CommandRoot& getCmdList(int n) {
    return *cmdList[n];
}
john
  • 85,011
  • 4
  • 57
  • 81