I Modified your Code slightly as under. And I get the desired result.
i.e.: when accessing a derived class reference from a base class pointer I get the compiler to map my function call correctly to the derived class' implementation.
I guess the following facts apply:
- A derived class would have to first implement(override: which doesn't say change the signature) the Virtual functions defined by the base class to be able to call/access them polymorphically.
- After a base class has implemented the virtual functions they can very well be overloaded.
- One other thing, If we see the VTable creation mechanism, Only when the derived class implements a virtual function defined at a base calss an entry for the same function name would be made. Otherwise the pointer A is still a map of the Class A and has no idea how to resolve the call to and ends up in implicitly casting the 5.1 double to int according to the implementation of function f in class A. this is pretty much what I mentioned in point#1
virtual functions and pure virtual functions are a means of providing/creating an interface which can be shared across different layers of your software, where the you simply share the interface and the can hide the implementation from the user. So having same function name/ interfaces defined by two classes would only cause more confusion.
#include<iostream>
using namespace std;
class A{
public:
virtual void f(int n){ cout << "A" << endl; }
};
class B :public A{
public:
void f(int f){ cout << "B" << endl; }
void f(float f){ cout << "B" << endl; }
};
int main(){
A*p= new B;
p->f(5.1);
}
Since there are lot of pros in this forum, ff there is anything incorrect in my answer, please put in your comments.
Thanks.