Question Details

No question body available.

Tags

c++ oop polymorphism encapsulation

Answers (1)

June 15, 2025 Score: 9 Rep: 37,246 Quality: High Completeness: 100%

You seem to expect that the method that is called will be determined on the actual runtime type of the object it is used with (here a Dog).

This is called runtime (or dynamic) dispatch and it is done in C++ only for virtual methods. In other words, you want Dog::speak to override Animal::speak, only virtual methods can be overidden.

For methods which are not virtual the call is determined at compile time, based on the type of the pointer (in your case Animal*) and not the actual object it points to.

A fixed version:

#include 

class Animal { public: //--vvvvvvv--------------- virtual void speak() { std::cout