C ++ function overload between base class and inherited class

consider the example below. I would have guessed that since it funcis virtual, than the decision about which implementation to call will be executed at runtime according to the type of instance (type B) and types of arguments (short or int)

However, after running this code, I got unexpected results when the type of pointer determines which function to jump, which completely violates my basic assumption about polymorphism ...

This leads to the question, where can I relate to the implementation of 2 func as an overload function?

Will someone tell me what is the reason for this result? thank

class A {
public:
    virtual void func(short x) { printf("A::func %d\n", x); }
};
class B : public A {
public:
    virtual void func(int x) { printf("B::func %d\n", x); }
};


int main(void)
{
    int n=2;
    short m=3;

    A* a = new B;
    a->func(n);
    a->func(m);

    B* bp = new B;
    bp->func(n);
    bp->func(m);
}
//output is : 
//A::func 2
//A::func 3
//B::func 2
//B::func 3
+4
source share
1 answer

, , . , A::func B, -:

class B : public A {
public:
    using A::func; //here
    virtual void func(int x) { printf("B::func %d\n", x); }
};

:

A::func 2
A::func 3
B::func 2
A::func 3

Live Demo

+5

All Articles