class Base {
public:
virtualint f() const {
cout << "Base::f()\n";
return 1;
}
virtualvoid f(string) const {}
virtualvoid g() const {}
};
class Derived4 : public Base {
public:
int f(int) const {
cout << "Derived4::f()\n";
return 4;
}
};
int main()
{
string s("hello");
Derived4 d4;
Base& br = d4; // Upcast
// br.f(1); // Derived version unavailable
br.f(); // why does it compile ?
br.f(s);// why does it compile ?
}
In derived : overloading f() of base .. so all base f() versions hidden .
Now , because of runtime binding , f() and f(s) of derived should be called , BUT they are hidden.
Q : What am i missing?
Q : br.f(1); does not compile because , during compile time , int f(int) is not present in Base . Am i correct?
There are three different functions named f:
- f() - virtual but never overridden
- f(string) - virtual but never overridden
- f(int) - not virtual, introduced by the derived class
Even if you properly override a virtual function, it is still possible to access it:
@LB,
I understood your answer , but in my question, i have not used br.Base::f() , but simply used Br.f() and it still compiles. Why? int f(int) has overloaded int f() , so all base class f() should not be visible to Derived.
Because of late binding, Derived::f() should be called , not Base::f().
But this is not what the code agrees with.
No, f() does not override f(int) because they are two completely different signatures. A function's name is only one part of what makes a function unique. The argument types and const/volatile/&/&& also factor into a function's signature.