Question about compiling temporary C ++ polymorphism?

The program below contains two show () functions in the parent and child classes, but the first show () function takes an FLOAT argument, and the second show () function takes an INT argument.

. If I call the show function (10.1234) by passing the float argument, it should call the class A show function (float a), but it will call class B show (int b).

#include<iostream>
using namespace std;

class A{
        float a;
public:
        void show(float a)
        {
                this->a = a;
                cout<<"\n A show() function called : "<<this->a<<endl;
        }
};

class B : public A{
        int b;
public:
        void show(int b)
        {
                this->b = b;
                cout<<"\n B show() function called : "<<this->b<<endl;
        }
};

int main()
{
        float i=10.1234;
        B Bobject;
        Bobject.show((float) i);
        return 0;
}

Conclusion:

B show() function called : 10

Expected Result:

A show() function called : 10.1234

Why did the g ++ compiler choose the wrong show()ie class B show(int b)function?

+3
source share
5 answers

, , , . , using:

using A::show;

:

Bobject.A::show(i);
+12

. virtual, .

+1

using.

class B : public A{
        int b;
public:
        using A::show;
};
+1

:
2 class A :
void Show(int a);
void Show(float a);

"" .

+1

, .

You can achieve what you want by adding this to definition B:

using A::show;

This will allow you to use both A show () and B show ().

+1
source

Source: https://habr.com/ru/post/1740656/


All Articles