Connecting Tech Pros Worldwide Forums | Help | Site Map

virtual function problem

cpp cpp is offline
Newbie
 
Join Date: Apr 2007
Posts: 5
#1: Oct 29 '07
I have a class X.
Then class Y is inheriting from X.

I have another class Base which is having a virtual function
virtual void fun(X& x){ }
Then i have class Derived which is inheriting form Base which overloads the fun
void fun(Y& y){ }

Now a base calss pointer is created pointing to derived class object.
and i am calling function fun() with that pointer. what i am expected is it will call void fun(Y& y){ } according to virtual mechanism. But it calls void fun(X& x){ }.

since i am using base class pointer (which is pointing to derived class object), to call a virtual function, then derived class' function will be called according to virtual mechanism. Then why this behaviour is happening..

cpp cpp is offline
Newbie
 
Join Date: Apr 2007
Posts: 5
#2: Oct 29 '07

re: virtual function problem


using base class pointer, only base class versions of the functions can be called. Here we are passing Y, which is derived from X. so base class version of fun(0 can take that reference.
Moderator
 
Join Date: Mar 2007
Location: North Bend Washington USA
Posts: 5,366
#3: Oct 29 '07

re: virtual function problem


Quote:

Originally Posted by cpp

I have another class Base which is having a virtual function
virtual void fun(X& x){ }
Then i have class Derived which is inheriting form Base which overloads the fun
void fun(Y& y){ }

For the virtual function mechanism to work you need to override rather than overload.

Your derived class should have void fun(X& x){ } just like the base class.
Reply