Virtual function behaviour

R

Rahul K

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.
 
S

Sunil Varma

Rahul said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,996
Messages
2,570,238
Members
46,826
Latest member
robinsontor

Latest Threads

Top