W
William Djaja Tjokroaminata
Hi,
As I am interfacing my code in C++ with a scripting language which is
written in C, I need to store pointers to objects in a class hierarchy:
ParentClass *obj1;
obj1 = new ParentClass (...);
... do things with obj1...
STORE_POINTER (scriptObj1, obj1);
DerivedClass *obj2;
obj2 = new DerivedClass (...);
...do things with obj2...
STORE_POINTER (scriptObj2, obj2);
However, when I try to retrieve an object, as I don't know which class the
object belongs to, I always use the base class (in this code segment I
just need the functionalities related to the ParentClass):
ParentClass *objN;
RETRIEVE_POINTER (scriptObjN, ParentClass, objN);
...do things with objN...
where STORE_POINTER and RETRIEVE_POINTER are some utility macros provided
by the scripting language.
I ran the code and I got a segmentation fault. I also notice that when
I printed out a pointer and cast it to different classes in the hierarchy,
I got different values:
cout << "pointer as parent = " << (ParentClass*) this << endl;
cout << "pointer as derived = " << (DerivedClass*) this << endl;
So my question is, in C++, is it unsafe to type cast a pointer to a
derived class to a pointer to a base class? (The other way around never
makes sense, of course.) If it is unsafe, what is the best way to solve
the above problem? Thanks.
Regards,
Bill
As I am interfacing my code in C++ with a scripting language which is
written in C, I need to store pointers to objects in a class hierarchy:
ParentClass *obj1;
obj1 = new ParentClass (...);
... do things with obj1...
STORE_POINTER (scriptObj1, obj1);
DerivedClass *obj2;
obj2 = new DerivedClass (...);
...do things with obj2...
STORE_POINTER (scriptObj2, obj2);
However, when I try to retrieve an object, as I don't know which class the
object belongs to, I always use the base class (in this code segment I
just need the functionalities related to the ParentClass):
ParentClass *objN;
RETRIEVE_POINTER (scriptObjN, ParentClass, objN);
...do things with objN...
where STORE_POINTER and RETRIEVE_POINTER are some utility macros provided
by the scripting language.
I ran the code and I got a segmentation fault. I also notice that when
I printed out a pointer and cast it to different classes in the hierarchy,
I got different values:
cout << "pointer as parent = " << (ParentClass*) this << endl;
cout << "pointer as derived = " << (DerivedClass*) this << endl;
So my question is, in C++, is it unsafe to type cast a pointer to a
derived class to a pointer to a base class? (The other way around never
makes sense, of course.) If it is unsafe, what is the best way to solve
the above problem? Thanks.
Regards,
Bill