Why is only derived class member function called?

44 views Asked by At

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;
}
1

There are 1 answers

0
Some programmer dude On BEST ANSWER

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.