Can't access derived class method from pointer of type base class

别等时光非礼了梦想. 提交于 2019-11-27 23:22:49

You can't. A pointer of type Person can only be used to access data/addresses(functions) that are part of the Person object. The compiler simply has no way of knowing what all classes could be deriving from Person and hence which operations are legal.

Have a look at Dynamic casting. MSDN Reference | Tutorial

In brief:

Player* pPlayer = dynamic_cast<Player*>(pPerson);
if (pPlayer) {
  //Use the pointer like a player pointer
  //Note: You can only call player functions from pPlayer, not pPerson
} else {
  //Use the pointer like a person pointer
}

Note that this casting is a runtime operation. At compile time, the compiler sees you using the Player pointer to access Player code, which it is happy to allow!

Disclaimer: I found your code tough to follow, so consider this an answer to your question in text

The problem you're facing is very similar to the classic animal/cat/dog example. The basic idea is you have a base class - Animal - and two classes that derive from it - Cat and Dog.

class Animal {
    public:
    Animal() {}
    virtual ~Animal() {}
};

class Dog : public Animal {
    public:
    Dog() : Animal() {}

    void bark() { std::cout << "Woof" << std::endl; }

    ~Dog() {}
}

class Cat : public Animal() {
    public:
    Cat() : Animal() {}

    void meow() { std::cout << "Meow" << std::endl; }

    ~Cat() {}
}

Now, if you declare a Cat or a Dog object, it's pretty obvious that you can call either bark() or meow(); but if you declare an Animal object, there's no way of knowing whether it's a Cat or a Dog, so you can't call either method.

In your case, you have Person as the base class and Player as the derived. You may further derive Person and have a new class, NonPlayer, so that Person would play the same role as Animal, and Player and NonPlayer would be Cat and Dog respectively.

If you really need to access Player methods from pointers to Person objects, you need to cast the Person* to Player* before. However, you need to be sure before that the pointer inside is a Player*. If it isn't, you'll most likely get a compilation error.

There are concepts of upcasting and downcasting which are essential to understand your problem. You can use the concept of dynimc_cast, this Link would be helpful to understand.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!