Search code examples
c++functioninheritanceoverloadingmethod-hiding

Why is only derived class member function called?


In the following code:
Please tell me why only derived class member function is called, is it because of hiding? And why an error doesn't occur in b.func(1.1);, the parameter is int x.

#include <bits/stdc++.h>

using namespace std;

class A {
public:
    virtual int func(float x)
    {
        cout << "A";
    }
};

class B : public A {
public:
    virtual int func(int x)
    {
        cout << "B";
    }
};

int main()
{
    B b;
    b.func(1);   // B
    b.func(1.1); // B

    return 0;
}

Solution

  • Yes it's because of hiding. This is one of the main reasons you should always add the special identifier override on functions you intend to override:

    class B : public A {
    public:
        virtual int func(int x) override  // <- Note the override here
        {
            cout << "B";
        }
    };
    

    This will cause the compiler to complain about not actually overriding.

    And floating point values can be implicitly converted to integers.