|
From: John-Philip T. <Joh...@ne...> - 2011-02-13 18:58:04
|
Good day,
I'm using a void* red-black tree to store a bunch of derived classes
and came across a peculiarity (much simplified below):
The code attached yields:
Integer is 12345
Now the integer is 4254256
Shifting the base address yields: 12345
main.cpp:
#include <stdio.h>
class Parent{
public:
int i;
};
class Child : public Parent{
public:
virtual int MyFunction(){return 0;}
};
int main(){
Parent* p;
Child * c;
void * v;
c = new Child;
c->i = 12345;
p = c;
printf("Integer is %d\n", p->i);
v = c;
p = (Parent*)v;
printf("Now the integer is %d\n", p->i);
p = (Parent*)((char*)v + 4);
printf("Shifting the base address yields: %d\n", p->i);
return 0;
}
Is this a bug in MinGW or just a rule in the C++ specification I'm
unaware of? Removing the "virtual" keyword removes the problem. I'm
using "tdm-gcc-4.5.1"
Also, as long as I cast to the base class when inserting into the tree
and then cast via the base class when taking things out of the tree
there is no problem. Only when I cast directly to void* (when
inserting) or the destination class (when querying) that the address
shift is present.
Regards,
John-Philip
|