Reputation: 523
A class Base
has a method void foo(float a)
. Class Sub
inherits publicly from Base
and has a method void foo(int a)
.
I have s
an instance of Sub
(stored in a Sub*
), and call s->foo(1.5)
. It's Sub::foo
that gets executed (with the argument truncated to 1
), rather than Base::foo
. Why is this?
I would naively expect it to execute the original method defined in Base
, seeing as the argument is a float. How could I achieve this instead?
Upvotes: 0
Views: 73
Reputation: 218268
With
struct Base
{
void foo(float a);
};
struct Sub : Base
{
void foo(int a); // Hides Base::Foo
};
Sub::foo
hides Base::foo
,
you have to add using
to allow both overloads.
struct Sub : Base
{
using Base::foo;
void foo(int a);
};
More details on using_declaration
And for your call:
Sub s;
s.foo(1.5); // Ambiguous with using, Sub::foo(int) without using.
without using, only one overload is considered, so Sub::foo(int)
is called.
With using
, both overloads are considered, but neither is a better match than the other, so it is ambiguous.
Upvotes: 4