Doubt on virtual functions

For everyone, just starting with C++ or programming at all. Ask newbie questions in this forum!

Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard

Doubt on virtual functions

Postby novino » Wed Sep 02, 2009 3:31 am

Class A inherits from B
B inherits from C
C inherits from D

Now D has 2 pure virtual functions x() and y(). i.e.
class D
{
x() = 0;
y() = 0;
}

Function x() is defined in Class C
Function y() is defined in both Class B and Class C

Now A is instantiated and object of class A calls function x(). i.e.
A aObj = new A;
aObj->x();

The call comes to the function defined in Class C
C::x()
{
.....
y();
}

Now y() is implemented both in class B and C.
At this point of time can anyone tell ideally where the flow should go. i.e.
C::x() will call C::y() or B::y() ?

The result i got from logs was quite different from what i was expecting, so if someone can give a proper explanation it would be appreciated :roll:

Thanks in advance.
novino
 
Posts: 1
Joined: Wed Sep 02, 2009 3:16 am

Re: Doubt on virtual functions

Postby Alvaro » Wed Sep 02, 2009 8:15 am

novino wrote:[...]
At this point of time can anyone tell ideally where the flow should go. i.e.
C::x() will call C::y() or B::y() ?

B::y() will be called. The way I think about it is that the `this' pointer passed to C::x is a pointer to a base class, so you'll get a virtual dispatch when it calls y().

Does that make any sense?
User avatar
Alvaro
Moderator
 
Posts: 5185
Joined: Mon Sep 22, 2003 4:57 pm
Location: NY, USA


Return to For Beginners

Who is online

Users browsing this forum: Google [Bot], Google Adsense [Bot] and 3 guests