Re: casting a void* into 2 base classes
Ulrich Eckhardt wrote:
hswerdfe wrote:
I have a wrapper object that returns a void*
Like So:
void* tmpVoid = myWrapper.GetObject();
The void* that it returns is one of 2 classes.
neither one has a base class.
how do I find out what class it is?
You can't. If there was a common baseclass with virtual functions, you might
be able to cast to that and then use RTTI (dynamic_cast).
and how do I cast it once I do?
static_cast
the solution I am thinking of now is bad I think.
that is to store the class name in the wrapper object.
CString className = myWrapper.GetClassName();
and then use that and do an old C Style Cast
CBase1* myBase1;
CBase2* myBase2;
if (className.Compare("CBase1") == 0)
myBase1 = (CBase1*)tmpVoid;
else if (className.Compare("myBase2") == 0)
myBase2= (myBase2*)tmpVoid;
For your own sake, please forget about the C style casts, these only serve
to hide errors. Also, are you aware that CString has overloaded
equality-comparison operators? You could have written
if(className == "CBase1")
...
which is generally considered much friendlier to read.
Now, concerning the design, you could as well return the type_id of each
possible class - this won't cost you any additional string storage. See the
typeid() operator in your C++ documentation.
Uli
Thanks, this helps a lot,
but I have issues storing the type_info
my Wrapper Class doesn't actually know what it is storing it just holds
a void*
I tried passing in the the type_info
of the base class
CWrap* = myWrapper = new CWrap(myBase1 , typeid(myBase1));
and storing the type_info in a member function
class CWrap
{
type_info& m_typeInfo;
}
But from my documentation, and compile errors (VC++6)
it looks like the copy constructor for type_info and assigment operator
are both declared private.
How do I store the type_info, from typeid()? if I can't make one, or
copy it? and from what I understand I can't get the Info from the void*.
cause this info is lost when you cast it to the void*.
Thanks again
How.