Mailing Lists: Apple Mailing Lists
Image of Mac OS face in stamp
Re: Accessing a C++ object's VTable directly without resorting to> assembly?
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Accessing a C++ object's VTable directly without resorting to> assembly?



Assuming single inheritance and since you are willing to resort to assembly,
you might as well try assuming that the vtable pointer is the first thing in
an object.

That is:

class Animal {public: Animal() { } virtual ~Animal() { } }; class Dog :
public Animal {public:  Dog() { } ~Dog() { } }; class Cat : public Animal
{public:  Cat() { } ~Cat() { } };

void ChangeAnimalToCat( Animal* a ) { Cat c; *(void**)a = *(void**)&c; }

It is in some ways very non portable and in some ways very portable. Like,
it's better than assembly imho. Some people reason, hey, if you are going to
be unportable, go all the way and be obvious about it. But to me, knowing an
object layout and manipulating it in C/C++ is much preferable to learning
assembly syntax, register names, calling conventions, moving code into
separate assembly source files, etc. (separate files called unportable.cpp
are still ok, but avoiding assembly source is good imho, though it matters
much less if you have already crossed that hump. if your product already has
assembly and you have examples to follow...)

In the face of multiple inheritance, the above may be correct but
insufficient. That is a typical implementation may have multiple vtable
pointers, one for each root in its type graph.

In the face of inheriting from classes without virtual functions the above
can be wrong, data can I believe often precede the vtable pointer.

In reality, of course, you know, you just can't do this. You have delete and
re-new the data. I'm not sure what placement new -- new (a) Cat() -- would
do. Maybe promising.

- Jay

 _______________________________________________
Do not post admin requests to the list. They will be ignored.
MPW-Dev mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:

This email sent to email@hidden



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2011 Apple Inc. All rights reserved.