class CBaseClass
{
//...
};
class CDerivedClass : public CBaseClass
{
//...
}
void Main()
{
CBaseClass *Base = new CBaseClass();
CBaseClass *Derived = new CDerivedClass();
if( typeid(Derived) == typeid(Base) )
printf("classes are the same");
else
printf("classes are different"); //I want it to return this, because I want to know EXACTLY what class the object is (base OR derived)
}
instanceof in C++
What is the C++ equivalent of the Java keyword instanceof?
I've checked out typeid(), but that function does not work just right for what I am trying to do. I want to be able to test what class an object is that was defined as a base class but instantiated as a derived class.
Here is simple code showing what I want to do:
[edited by - doctorsixstring on June 5, 2002 3:56:47 PM]
You can provide a member function which tell''s you what type it is. It just has to return a idnumber or a string.
That sounds like a good idea. If no one else has any ideas on using a single keyword, I will go with that.
-Mike
-Mike
You can also try a dynamic_cast to a pointer to the derived type. If it returns null, then base* doesn''t point to a derived. If you get a valid pointer, then it can be a derived
something like this...
something like this...
class base;class derived:public base;base* b=new base();base* d=new derived();if(dynamic_cast<derived*>(b)) //derivedelse //baseif(dynamic_cast<derived*>(d)) //derivedelse //base
sjelkjd: The compiler gives me an error, stating that my base class is not a polymorphic type.
fallenang3l: If I give typeid() a straight pointer to an object, it returns a string like this: "class CBase *". If I add the * to the parameter, it returns this: "class CBase *".
Any other ideas?
fallenang3l: If I give typeid() a straight pointer to an object, it returns a string like this: "class CBase *". If I add the * to the parameter, it returns this: "class CBase *".
Any other ideas?
quote:Original post by doctorsixstring
sjelkjd: The compiler gives me an error, stating that my base class is not a polymorphic type.
You have to enable RTTI: Project->Settings->c++ Language
not only that, dynamic_cast only works on base classes that define at least one virtual function.
If you derive all your possible objects from an interface (say, CRTTI), then you can include a pure virtual method in that, and make all your deriving classes implement it. That method can return the type.
Although, I found my solution to be much more useful in a ''COM-style'' situation, when you want to find out if an object supports a particular interface.
Superpig
- saving pigs from untimely fates
- sleeps in a ham-mock at www.thebinaryrefinery.cjb.net
Although, I found my solution to be much more useful in a ''COM-style'' situation, when you want to find out if an object supports a particular interface.
Superpig
- saving pigs from untimely fates
- sleeps in a ham-mock at www.thebinaryrefinery.cjb.net
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement