Base class pointer vs inherited class pointer?

后端 未结 8 1183
独厮守ぢ
独厮守ぢ 2021-01-05 23:11

Suppose I have a class Dog that inherits from a class Animal. What is the difference between these two lines of code?

    Animal *a         


        
8条回答
  •  天命终不由人
    2021-01-05 23:50

    The answer to this question is a giant: It depends

    There are numerous ways in which the type of the pointer could become important. C++ is a very complex language and one of the ways it shows up is with inheritance.

    Lets take a short example to demonstrate one of the many ways in which this could matter.

    class Animal {
    public:
      virtual void MakeSound(const char* pNoise) { ... }
      virtual void MakeSound() { ... }
    };
    
    class Dog : public Animal {
    public:
      virtual void MakeSound() {... }
    };
    
    int main() {
      Animal* a = new Dog();
      Dog* d = new Dog();
      a->MakeSound("bark");
      d->MakeSound("bark"); // Does not compile
      return 0;
    }
    

    The reason why is a quirk of the way C++ does name lookup. In Short: When looking for a method to call C++ will walk the type hierarchy looking for the first type which has a method of the matching name. It will then look for a correct overload from the methods with that name declared on that type. Since Dog only declares a MakeSound method with no parameters, no overload matches and it fails to compile.

提交回复
热议问题