Base class function is executed despite of overriding

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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 I write

1
2
GentleDog pet;
pet.bark();


Of course the GentleDog::bark() will be called.

But why wasn't it the case in the first example?
Last edited on
closed account (48T7M4Gy)
But why wasn't it the case in the first example?

Because if you trust dog's with human constructs like inheritance they will still obey their master.
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().
Last edited on
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#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
    {
        virtual void bark() const
        { std::cout << "A generic dog has spoken\n" ; }
    } ;

    struct GentleDog : public Dog
    {
        virtual void 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" ; }
    };
}

http://coliru.stacked-crooked.com/a/3ae492ccc6524d01
Topic archived. No new replies allowed.