I came across this code written in C++ :
#include<iostream>
using namespace std;
class Base {
public:
virtual int fun(int i) { cout << "Base::fun(int i) called"; }
};
class Derived: public Base {
private:
int fun(int x) { cout << "Derived::fun(int x) called"; }
};
int main()
{
Base *ptr = new Derived;
ptr->fun(10);
return 0;
}
Output:
Derived::fun(int x) called
While in the following case :
#include<iostream>
using namespace std;
class Base {
public:
virtual int fun(int i) { }
};
class Derived: public Base {
private:
int fun(int x) { }
};
int main()
{
Derived d;
d.fun(1);
return 0;
}
Output :
Compiler Error.
Can anyone explain why is this happening ? In the first case , a private function is being called through an object.
d.fun(1)
isn't a virtual function call, butptr->fun(10)
is. – Weesevirtual int
but an integer is not being returned in those functions.. – Glidden->
or.
operators. It only has to do with the type you use to call the method: If you call the method throughBase
, it will compile as the methodBase::fun
is public. If you call the method throughDerived
, it will fail asDerived::fun
is private. . . Now,fun
is virtual, meaning that calling it means, by default, dynamic binding... Unless the compiler can guarantee the exact type of the object at compile time. In that case, the call will be optimized, to be statically resolved to the right method. – Sacring