Reputation: 54113
Say I have base class A. it has method
void foo(A* a);
It also has method
void foo(B* b);
B inherits from A.
Say I now have a B instance but it is an A* ex:
A* a = new B();
If I were to call
someA.foo(a);
Would this call the A* implementation or B* implementation of the method?
I'm providing an A* to the method, but what that object actually is is a B().
Thanks
Upvotes: 1
Views: 120
Reputation: 1748
I would expect it to use the foo(A *)
method because the static type is A
.
But, like someone said, add some logging and try checking which one is being executed.
Upvotes: 0
Reputation: 12675
Because A::foo(A*)
and B::foo(B*)
have different signatures (types of their arguments), the compiler treats them as totally different functions. If instead of calling both methods foo()
you had called one A::bar(A*)
and another B::baz(B*)
, you would get identical behavior.
foo(A*)
is a method of all objects of type A
, and all objects of type B
are also objects of type A
because B
is derived from A
. So foo()
is indeed a method of the object someA
, inherited from the parent A
class. This method, the A
method, is the one that gets called.
Upvotes: 0
Reputation: 17176
Well, two things will happen. First of all the determination of which function to call:
A* a = new B();
foo(a);
Here you pass a variable of type A* (C++ = static typed, remember) to foo, this will as usual call foo(A* a)
, nothing different from any other function overloading. If you were to call foo(new B())
it would use the implicit type B*
and end up calling foo(B* b)
. Nothing new here, plain old function overloading. Note that only when foo(B*)
is not present it will fall back to a more generic version because of inheritance.
Now in your example we come to the calling of this function:
void foo(A* a)
{
a->foo();
}
Well, again, standard C++ calling conventions apply, including polymorphism. This means if you have declared foo as virtual the vtable will be constructed in such a way that the foo method of B will be called for your example (as the object is created as type B). If A::foo()
is not declared as virtual, the method of A itself will be called.
Upvotes: 3
Reputation: 131789
Function overloads are selected based on the static type of the passed parameter. The static type of a
is A*
, only its dynamic type is B
. Go figure.
Upvotes: 6