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
Well, two things will happen. First of all the determination of which function to call:
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 callfoo(new B())it would use the implicit typeB*and end up callingfoo(B* b). Nothing new here, plain old function overloading. Note that only whenfoo(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:
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.