could you please help me.
I am passing self to a pure virtual function of itself.
n->dataCallback(handler, n, hangup);
where n is my class pointer and dataCallback is its own (pure) virtual function (I know it makes no sense, I just wonder why it happens what I describe below).
so now in the declaration:
void MyClass::dataCallback(int handler, void *cbData, bool hangup) {
MyClass *This = (MyClass*) cbData;
....
}
Now when I compare This (the varaiable above) to this (the pointer of the object) at runtime I get:
- The values of the poiners (the addresses of the object) are different.
- When checking a memeber varaible (This->member) I find different values in them. (The correct value is in this, whereas This contains an undefined (to me random) value. Note, that on the caller side the value is of course correct so it seems to magically change during the call itself, and there is no other code in between.
How on earth is this possible? Any Idea?
I’ve spent 2 hours meditating on this, also asked other programmers with no results.
If you have multiple inheritance, casting a pointer to each of the parent classes may change the pointer address. Consider the following:
The internal layout of class C will contain two integers
aandb. If you cast a pointer fromC*toA*all is well. If you cast it toB*, the pointer will need to be adjusted because the first element in aBmust be the integerb!If you do a cast where both types are known to the compiler, it will do the adjusting in a way which is invisible to you – it just works. The compiler knows what the proper adjustment should be. When you cast to
void*this mechanism gets broken.