sharptooth
sharptooth

Reputation: 170509

Is vptr ever located not at start of object?

According to MSDN, __RTDynamicCast() function is used to implement dynamic_cast in Visual C++. One of its parameters is LONG VfDelta that is described as "offset of virtual function pointer in object".

AFAIK the vptr is always located at start of object, so offset will always be zero. I've looked closely at disassembly of various code snippets using dynamic_cast and I've never seen anything but zero being passed in place of this parameter.

Is vptr ever located anywhere but the object start? Can this offset be anything but zero?

Upvotes: 4

Views: 1926

Answers (3)

Analog File
Analog File

Reputation: 5316

I do not know what Microsoft does, but it's not always true that the vtable pointer is located at offset zero. An example of cases where it may not be is for multiple inheritance (especially if virtual base classes are involved).

Edit:

I'll expand this a bit with examples.

If the first base or a class does not have a vtbl, the derived class will not have a vtbl pointer at offset 0 (such inheritance is bad practice, but is permitted by the language).

If there is a virtual base, the derived class will generally have a pointer to the virtual base at offset 0, not a vtbl pointer.

Upvotes: 2

crazyjul
crazyjul

Reputation: 2539

This functionality is used when virtual inheritance exits ( think about the diamond inheritance chart ). This offset is the offset of the class itself inside the object.

If B and C derives from A, and D derives from both.

   A
 /   \
B     C
 \   /
   D

Then B and C could be in either order in D. This is where the offset comes into action. So when you dynamic_cast an object of type A to type B, it might be different depending on wether the instance is of type B or D.

Finally to illustrate, here is possible layout of different class

Class B:  Class C:   class D:
 | A |      | A |     | A |
 | B |      | C |     | C |
                      | B |
                      | D |

In this case the offset of virtual function table of B can be either in 0 ( B instance case ), or sizeof( A ) + sizeof( C ) ( D instance case )

Upvotes: 1

Andrew
Andrew

Reputation: 24846

In case of multiple inheritance there are more then one vptr and you need the offset. Take a look here: http://hacksoflife.blogspot.com/2007/02/c-objects-part-3-multiple-inheritance.html

Upvotes: 5

Related Questions