class Dog
{
public:
void bark()
{
cout << "A generic dog has spoken" << endl;
}
void seeCat()
{
bark();
}
};
class GentleDog : public Dog
{
public:
void bark()
{
cout << "woof-woof I won't eat you woof-woof!" << endl;
}
};
The bark() method is overridden in the GentleDog derived class.
BUT, if I write:
1 2
GentleDog pet;
pet.seeCat();
The pet.seeCat() will call the base class Dog::seeCat() method since there is no override.
The Dog::seeCat() method calls the Dog's bark() method, not GentleDog's one.
THE SOLUTION IS SIMPLE: add 'virtual' to the bark() method in the Dog class
No, I didn't want to know the solution.
I want to know WHY Dog::bark() was called although we used a GentleDog object?
If you don't use virtual the function is overloaded, not overriden. Which version of overloaded functions to call is always decided at compile time based on the static types involved. Inside Dog::seeCat() the static type of the object (*this) is Dog so that is why it calls Dog::bark().
Tip: Use the override specifier when the intent is to override a virtual function, and the compiler will catch situations where the intent is not met. http://en.cppreference.com/w/cpp/language/override
#include <iostream>
namespace one
{
struct Dog
{
void bark()
{ std::cout << "A generic dog has spoken\n" ; }
} ;
struct GentleDog : public Dog
{
void bark() override // *** oops: not virtual
// *** error: only virtual member functions can be marked 'override'
{ std::cout << "woof-woof I won't eat you woof-woof!\n" ; }
};
}
namespace two
{
struct Dog
{
virtualvoid bark() const
{ std::cout << "A generic dog has spoken\n" ; }
} ;
struct GentleDog : public Dog
{
virtualvoid bark() override // *** oops: forgot the const
// *** error: 'bark' marked 'override' but does not override any member functions
{ std::cout << "woof-woof I won't eat you woof-woof!\n" ; }
};
}