Search code examples
c++multiple-inheritancevirtual-functions

Virtual function does not overrides to latest inheriting object


I have 3 classes: A, B, C. B inherits from A, and C inherits from B (so C is grandchild of A).
Every object has function talk() that displays text, in A and B it's virtual.
Let have outside function call(A &a), that takes object A by reference, and calls function talk().
Sending object C to the function, it uses talk() from B instead of C, even that at B talk() is virtual.
Why it is so? How to make it call version from C?

    #include <iostream>
    using namespace std;

    class A {
    public:
        virtual void talk() = 0;
        virtual void say() = 0;
    };

    class B : public A  {
    public:
        virtual void talk() // Why C does not overrides this?
        {   cout << "hello\n";  }   
    };

    class C : public B  {
    public:
        void talk (int a)   // It should override B.talk();
        { cout << "bye\n";}
        virtual void say()  { cout << "my name\n"; }
    };

    void call(A &a) {
        a.talk();   // Why does it call virtual talk() from B rather than from C?
        a.say();    // This was found so it knows about object C
    }

    int main()  {
        C c;
        call(c);
        system("PAUSE");
        return 0;
    }

I'd expect that call(A &a) takes the furthest inheritance version if every class between has virtual talk()


Solution

  • In your example, C.talk(int) doesn't override B.talk() because C.talk takes an int as a parameter, so it's an entirely different function.

    You can add override after a function declaration to get the compiler to check if it actually overrides anything:

    class C : public B  {
       public:
        // Here, the compiler complains because there's no talk(int) method
        // That it can override
        void talk (int a) override;
        { cout << "bye\n";}
        virtual void say()  { cout << "my name\n"; }
    };