CodeVomit
CodeVomit

Reputation: 749

C++ check if object is a descendant of a given superclass

I have a pointer to an object, I want to know if that object is either of type of a given class or of type that is a subclass of the given class in C++.

Upvotes: 2

Views: 1301

Answers (2)

gvd
gvd

Reputation: 1831

Use dynamic_cast:

class A {
public:
    virtual ~A() = default;
};
class B : public A {    
};
B * obj = new B();
auto obj2 = dynamic_cast<A*>(obj);
if (obj2 != nullptr) {
    std::cout << "B is an A" << std::endl;
}

Upvotes: 5

Steve Jessop
Steve Jessop

Reputation: 279255

The pointer you start with must have a type. Let's say that type is T*. Let's say the "given class" is G. I think (although I may be wrong) that it's the complete type of the object that you want to know about, not the relation between the types T and G.

If T is a class type with at least one virtual function, then you can do the test you want on a pointer ptr like this:

if (dynamic_cast<G*>(ptr)) {
    // then the complete type of your object is either G or a subclass
} else {
    // it isn't
}

If T is not a class type, or if it doesn't have a virtual function, then what you want to do is not possible. You'll have to find a more useful static type for the pointer.

If all you want to know is whether G is "either a base of or the same as" T then you don't need dynamic_cast or for there to be a virtual function. You just need std::is_base_of.

Upvotes: 2

Related Questions