views:

136

answers:

4

Consider the following class hierarchy:

  • base class Object with a virtual method foo()
  • an arbitrary hierarchy with multiple inheritance (virtual and non-virtual); each class is a subtype of Object; some of them override foo(), some don't
  • a class X from this hierarchy, not overriding foo()

How to determine which method will be executed upon a call of foo() on an object of class X in C++?

(I'm looking for the algorithm, not any specific case.)

A: 

If you are talking about G++ a vtable (Virtual Method Table) is used, you can get more specific details here. Not sure if every C++ compiler uses the same approach but I would say yes

Jack
+4  A: 
KennyTM
http://www.csci.csusb.edu/dick/c++std/cd2/derived.html#class.member.lookup
pascal
Thanks for the detailed description :) That's exactly what I needed.
Kos
+1  A: 

Some detailed description with code.

vtable and vptr

vtable

Virtual Functions

DumbCoder
A: 

If a method of a base class is virtual, every call to it through base or derived pointer/reference will call the appropriate method (The one furthest down the inheritance tree). If the method was declared virtual, you can't have it any other way later : declaring it virtual (or not) in derived classes won't change anything.

fingerprint211b
Yes, but what I'm asking is basically which is "the appropriate method", which is non-trivial if the inheritance tree is, well, not a tree.Python has a nice doc on how they do it: http://www.python.org/download/releases/2.3/mro/ ; I'm trying to come up with a similar explanation for C++.
Kos