Base class pointer vs inherited class pointer?

后端 未结 8 1199
独厮守ぢ
独厮守ぢ 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:49

    You must always remember there are 2 parts in every class, the data and the interface.

    Your code truly created 2 Dog objects on the heap. Which means the data is of Dog. This object is of size the sum of all data members Dog + Animal + the vtable pointer.

    The ponters a and d (lvalues) differ as from a interface point of view. Which determines how you can treat them code wise. So even though Animal* a is really a Dog, you could not access a->Bark() even if Dog::Bark() existed. d->Bark() would have worked fine.

    Adding the vtable back into the picture, assuming the interface of Animal had Animal::Move a generic Move() and that Dog really overwriten with a Dog::Move() { like a dog }.

    Even if you had Animal a* and performed a->Move() thanks to the vtable you would actually Move() { like a dog }. This happens because Animal::Move() was a (virtual) function pointer re-pointed to Dog's::Move() while constructing Dog().

提交回复
热议问题