C++ Equivalent of Java'S Instanceof

C++ equivalent of java's instanceof

Try using:

if(NewType* v = dynamic_cast<NewType*>(old)) {
// old was safely casted to NewType
v->doSomething();
}

This requires your compiler to have rtti support enabled.

EDIT:
I've had some good comments on this answer!

Every time you need to use a dynamic_cast (or instanceof) you'd better ask yourself whether it's a necessary thing. It's generally a sign of poor design.

Typical workarounds is putting the special behaviour for the class you are checking for into a virtual function on the base class or perhaps introducing something like a visitor where you can introduce specific behaviour for subclasses without changing the interface (except for adding the visitor acceptance interface of course).

As pointed out dynamic_cast doesn't come for free. A simple and consistently performing hack that handles most (but not all cases) is basically adding an enum representing all the possible types your class can have and check whether you got the right one.

if(old->getType() == BOX) {
Box* box = static_cast<Box*>(old);
// Do something box specific
}

This is not good oo design, but it can be a workaround and its cost is more or less only a virtual function call. It also works regardless of RTTI is enabled or not.

Note that this approach doesn't support multiple levels of inheritance so if you're not careful you might end with code looking like this:

// Here we have a SpecialBox class that inherits Box, since it has its own type
// we must check for both BOX or SPECIAL_BOX
if(old->getType() == BOX || old->getType() == SPECIAL_BOX) {
Box* box = static_cast<Box*>(old);
// Do something box specific
}

(object instanceof C) what is the type of C?

You can use the isInstance method of Class.

Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.

So you would write

if (objClass.isInstance(obj)) ...

If you want to do this generically, you can use .cast to convert to the type represented by objClass.

public <T> void method(Object obj, Class<T> objClass) {
if(objClass.isInstance(obj)) {
T t = objClass.cast(obj);
//do something with t instead of obj
}
}

What is an equivalent to instanceof in C++?

There is no way to check class type without RTTI or it's home brew substitution. If application compiled without RTTI information about type is not stored anywhere.

what is the C++ version of Java's instanceof? : checking, not casting

By using dynamic_cast<T> you can attempt to cast to a derived class pointer. If it succeeds, then that's the right type. If it fails, then it's not.

if( dynamic_cast<Book*>(item) ) { // stuff }

C++ does offer limited compile time ways to check certain things. For example, you can check if something is a derived class with
std::is_base_of<base, derived>

There is also std::is_same<type1, type2>

The problem is that these are compile time resolutions. Runtime-polymorphism means naturally you can't truly know before run-time what your concrete types are.

Edit: Adding some info that's probably more useful to your situation.

The line cout << item << endl;, what you're doing isn't going to solve your problem from what I can tell. Dynamic type identification is bad design anyways, you should avoid it generally.

No, instead you need to take advantage of polymorphism in this case. You'll want to make operator<< virtual. Your subclasses will have their own ways of printing data.

When cout << item << endl; is invoked, you won't need to figure out the type. The vtable lookup will happen for you, and you'll get the desired behaviour.

The only catch is you might need a middleman between your overload and the free operator>>. Essentially you'll have a virtual operator like I mentioned, but you'll want an overload to make sure that's invoked correctly since it's a class member and not a free function.

Look here for details

instanceof equivalent in C++

A dynamic_cast will check to see if you can downcast o to Tile. If you can, it will return a valid Tile*, else it will return a null Tile*:

void World::add(WorldObject* o) {
content.push_back(o);
if (Tile* t = dynamic_cast<Tile*>(o)) {
tiles.push_back(t);
}
}

In Objective-C, what is the equivalent of Java's instanceof keyword?

Try [myObject class] for returning the class of an object.

You can make exact comparisons with:

if ([myObject class] == [MyClass class])

but not by using directly MyClass identifier.

Similarily, you can find if the object is of a subclass of your class with:

if ([myObject isKindOfClass:[AnObject class]])

as suggested by Jon Skeet and zoul.

What is the C# equivalent to Java's isInstance()?

The equivalent of Java’s obj.getClass().isInstance(otherObj) in C# is as follows:

bool result = obj.GetType().IsAssignableFrom(otherObj.GetType());

Note that while both Java and C# work on the runtime type object (Java java.lang.Class ≣ C# System.Type) of an obj (via .getClass() vs .getType()), Java’s isInstance takes an object as its argument, whereas C#’s IsAssignableFrom expects another System.Type object.

Is c# operator just like instanceof in java?

It's 'safe'. At least it's safer to use this check, rather than just cast and assume the type! You may prefer to use the as operator, which performs the cast to the required type if appropriate, or returns null otherwise. Just remember to check for null.

But often an explicit type check is an indication that something is not quite right with your model. Sometimes it's unavoidable, but if you're doing this a lot, I would take a step back and reconsider your model.



Related Topics



Leave a reply



Submit