instanceof in C++?

M

Michael

Hi All,

Is there a function similar to Java's instanceof in C++?
To ask the question a different way, if I have a base class and two derived
classes, how can I tell which one of the derived classes a particular object
belongs to?

BaseClass* base;

if(some_test){
base = new Class1;
} else {
base = new Class2;
}

How can I tell if I created a Class1 or Class2 object from the object?

Thanks for your help

Michael
 
M

m_schellens

Hi All,

Is there a function similar to Java's instanceof in C++?
To ask the question a different way, if I have a base class and two derived
classes, how can I tell which one of the derived classes a particular object
belongs to?

BaseClass* base;

if(some_test){
base = new Class1;} else {

base = new Class2;

}

How can I tell if I created a Class1 or Class2 object from the object?

Thanks for your help

Michael

dynamic_cast is your friend.

Cheers
Marc
 
S

Stefan Naewe

Hi All,

Is there a function similar to Java's instanceof in C++?
To ask the question a different way, if I have a base class and two derived
classes, how can I tell which one of the derived classes a particular object
belongs to?

BaseClass* base;

if(some_test){
base = new Class1;
} else {
base = new Class2;
}

How can I tell if I created a Class1 or Class2 object from the object?

Use dynamic_cast<> :

if(Class1* c1 = dynamic_cast<Class1*>(base))
// it's a Class1*
else if (Class2* c2 = dynamic_cast<Class2*>(base))
// it's a Class2*


But: Frequent use of dynamic_cast<> is a smell of bad design!


S.
 
M

Mike Wahler

Michael said:
Hi All,

Is there a function similar to Java's instanceof in C++?
To ask the question a different way, if I have a base class and two
derived classes, how can I tell which one of the derived classes a
particular object belongs to?

BaseClass* base;

if(some_test){
base = new Class1;
} else {
base = new Class2;
}

How can I tell if I created a Class1 or Class2 object from the object?

You could use 'dynamic_cast', but the whole point of derivation
(with a reasonable design), is that you should not *need* to know
which derived type it is. From an interface standpoint, both
your instances are type 'base' (Isn't that why you used type 'base*'
with 'new'?). If there were a situation where the derived type is
significant,
I'd think you'd write:

Class1 *c = new Class1;

-Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
474,102
Messages
2,570,645
Members
47,245
Latest member
ShannonEat

Latest Threads

Top