Archived

This topic is now archived and is closed to further replies.

instanceof in C++

This topic is 5663 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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:
  
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)


}
  
[edited by - doctorsixstring on June 5, 2002 3:56:47 PM]

Share this post


Link to post
Share on other sites
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...

  
class base;
class derived:public base;

base* b=new base();
base* d=new derived();
if(dynamic_cast<derived*>(b))
//derived

else
//base

if(dynamic_cast<derived*>(d))
//derived

else
//base


Share this post


Link to post
Share on other sites
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?


Share this post


Link to post
Share on other sites
Guest Anonymous Poster
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

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
yes, that''s the real question. You almost certainly don''t have a valid reason, just a bad design. True, sometimes various casting techniques are required, either because the language lacks a feature you need, or more commonly that you are dealing with a non idea code base. But as a hobbyest making your own programs from scratch you will almost never need to do something like what you are asking. Maybe you had to in java, but C++ is a different language. instanceof simply isn''t needed, neither is a common base class. (Even things like CObject aren''t common, they''re just common to one API)

Share this post


Link to post
Share on other sites
quote:
Original post by Anonymous Poster
yes, that''s the real question. You almost certainly don''t have a valid reason, just a bad design. True, sometimes various casting techniques are required, either because the language lacks a feature you need, or more commonly that you are dealing with a non idea code base. But as a hobbyest making your own programs from scratch you will almost never need to do something like what you are asking. Maybe you had to in java, but C++ is a different language.

Why don''t you try to answer his question instead of telling him he doesn''t need to do it. Just because you can''t think of a use for something does not mean its not useful. instanceof is not required in Java, but it makes thing easier by allowing you a single control point for multiple derived classes. Like if you are bulding a GUI you can have all the event listeners go to one area and then use instanceof to decide what to do with the message.

quote:
Original post by Anonymous Poster
instanceof simply isn''t needed, neither is a common base class. (Even things like CObject aren''t common, they''re just common to one API)

When they made a specs for C++, they were going to go with a common base class, but decided against it because it would be to slow. And trying to get all the C coders to switch to C++, slow code would not do.


doctorsixstring, sorry I do not know how to do it either. Since I learned Java, I found that instanceof was useful, but could never find a similar construct in C++.

---
Make it work.
Make it fast.

"Commmmpuuuuterrrr.." --Scotty Star Trek IV:The Voyage Home

Share this post


Link to post
Share on other sites
Thanks, CaptainJester. I've decided to go with having a function that returns an ID # based on the class.

I was originally angered that my university decided to switch from C++ to Java, as I have been programming for a few years in C++ and would have much rather taken C++ based programming classes. I couldn't find much to like about Java, until today . But don't get me wrong, C++ w/ Win32 and DirectX is still my preferred programming tools.

In my app, I have a base class called CDevice, and numerous derived classes, each based on various real-world instruments manufactured by my employer. The reason I would have liked to find an instanceof equivalent is because I need a way to easily differentiate between each derived device class, and being able to use a simple keyword to identify them (like instanceof) would be very useful.

Basically, my app has a large array of the base class CDevice. Each entry in the array will be set to one of the derived classes, and later will be updated according to its type.


    
CDevice Devices[32];
Devices[0] = new CSubDeviceA(...);
Devices[1] = new CSubDeviceB(...);
Devices[2] = new CSubDeviceC(...);

for(int i=0; i<32; i++)
{
if( Devices[i].GetClassID == 0 )
{}
else if( Devices[i].GetClassID == 1 )
{}
else if( Devices[i].GetClassID == 2 )
{}
}



is crucial in order to easily use them. I think that having each class simply return an ID # of sorts will work well enough.

One last question: Would it be better to declare any function I will ever use in a derived class as a virtual function in the base class? Is this the proper way to go about this?

Thanks for all the replies,
-Mike


[edited by - doctorsixstring on June 6, 2002 9:58:11 AM]

Share this post


Link to post
Share on other sites
Is there a reason why you can't use dynamic_cast?

If you do a dynamic_cast of a pointer to a given type - it will return NULL if it is not that type - so that makes it an easy way to check eg

Then to check if both are a given type just dynamic cast both of them

your example

    
if ( dynamic_cast<Derived*>( derived ) )
printf( "Derived" )


The question is, if you are doing this - to compare two or more different class instances at runtime you may want to think if there is another way to accomplish what you need to do.

Your example doesn't hint at the goal so it is hard to say.

The main issue with this is that it is case-analysis of type, which almost always is better accomplished via polymorphism - or sometimes if you need it, double or multiple dispatch.

[edited by - SteveC on June 6, 2002 10:21:58 AM]

Share this post


Link to post
Share on other sites
You can do something like this:

  
class CDevice {
...
virtual void DoStuff(...)=0;
};

CDevice* Devices[32];
Devices[0] = new CSubDeviceA(...);
Devices[1] = new CSubDeviceB(...);
Devices[2] = new CSubDeviceC(...);

for(int i=0; i<32; i++)
{
Devices[i]->DoStuff();
}


Much cleaner! And don''t ever assign a derived to a base object, only a base pointer/reference.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
yes sjelkjd has the right idea, use virtual functions. Then computer will handle all of the instanceof stuff in the background for you. The only issue is that you might have trouble passing the right parameters in. I''m not sure if there is a complete solution for that issue, but in most actual situations I''ve found that it isn''t too bad and I''m sure you''ll think of something.

Share this post


Link to post
Share on other sites
quote:
Original post by CaptainJester
Why don''t you try to answer his question instead of telling him he doesn''t need to do it. Just because you can''t think of a use for something does not mean its not useful.

Hey relax, we didn''t say RTTI IS THE DEVIL!!! We just said ''there''s probably a better way''. Like using virtual methods to handle widget events, instead of a high-maintaince switch or nest of if''s.

quote:

doctorsixstring, sorry I do not know how to do it either. Since I learned Java, I found that instanceof was useful, but could never find a similar construct in C++.



You need to enabled RTTI in the compiler settings, then you can compare results of typeid (type_info&''s)

  
if (typeid(*base) == typeid(Derive))
{//base points to a Derive class

}

Share this post


Link to post
Share on other sites
quote:
Original post by Magmai Kai Holmlor [quote]Original post by Magmai Kai Holmlor
Hey relax, we didn''t say RTTI IS THE DEVIL!!! We just said ''there''s probably a better way''. Like using virtual methods to handle widget events, instead of a high-maintaince switch or nest of if''s.


Sorry, I have learned both C++ and Java, and while I still prefer C++, I hate to see people bash Java just because. I found that learning Java made me a better C++ programmer.

Thanks for the typeid info.

---
Make it work.
Make it fast.

"Commmmpuuuuterrrr.." --Scotty Star Trek IV:The Voyage Home

Share this post


Link to post
Share on other sites
quote:

When they made a specs for C++, they were going to go with a common base class, but decided against it because it would be to slow. And trying to get all the C coders to switch to C++, slow code would not do.


I''m kind of curious of where you found this information?

Share this post


Link to post
Share on other sites
I don''t remember. I just remember when I was reading an article/book on C++ it came to a spot where they were comparing the use of a base class in Java to C++ not having one and said that they(Stroustrup?) opted not to go for it as it would produce slower code.

---
Make it work.
Make it fast.

"Commmmpuuuuterrrr.." --Scotty Star Trek IV:The Voyage Home

Share this post


Link to post
Share on other sites