user1899020
user1899020

Reputation: 13575

Does C++ have existing method to check if an object is a derived-typed object?

Does C++ have existing method to check if an object is a derived-typed object? For example,

class A
{};

class B : public A
{};

A* p;

And check if p points to B.

Upvotes: 3

Views: 2589

Answers (4)

doug
doug

Reputation: 4299

If the object in question is not a polymorphic class it is possible to determine whether a class object pointed to has a specific base class at compile time. This sometimes occurs in template code where different base classes are possible.

You use std::is_base_of as follows: Note that you must also use std::remove_reference since *p is an lvalue and decltype() produces a reference.

#include  <type_traits>
#include <iostream>

class A {};
class B : public A{};

int main() {
    A a;
    B b;
    A* pa=&a;
    B* pb=&b;
    std::cout << std::is_base_of<A, B>::value << "\n";  // true
    std::cout << std::is_base_of<B, A>::value << "\n";  // false
    std::cout << std::is_base_of<A, std::remove_reference<decltype(*pb)>::type>::value << "\n";  // true
    std::cout << std::is_base_of<B, std::remove_reference<decltype(*pa)>::type>::value << "\n";  // false
}

Upvotes: 1

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Does C++ have existing method to check if an object is a derived-typed object?

There are actually two ways to achieve this:

A* p = new B(); 
B* pB = static_cast<B*>(p); // Checks if B is related to A in an inheritance 
     // ^^^^^^^^^^^^^^^^^^^    hierarchy. Fails to compile if not.

A* pA = new B();
B* pB = dynamic_cast<B*>(pA); // Checks if pA actually points to an instance of B
     // ^^^^^^^^^^^^^^^^^^^^     at runtime, and returns nullptr if not
if(pB) {
  // do stuff with B
}

The latter example requires you have a virtual base class:

class A { 
public:
    virtual ~A() {} // <<<<<<<<<<<<<<<<<<
};

Upvotes: 1

R Sahu
R Sahu

Reputation: 206717

And check if p points to B.

You can use dynamic_cast for that, if there is at least one virtual member function in the class. It is common to make the destructor virtual.

class A
{
   virtual ~A() {}
};

and then,

B* bPtr = dynamic_cast<B*>(p);
if ( bPtr )
{
   // Use the pointer
}

Upvotes: 5

T.C.
T.C.

Reputation: 137395

If the class is polymorphic (i.e., has at least one virtual member function), you can use dynamic_cast or typeid.

Otherwise, no. Keeping track of an object's dynamic type has a cost, and the language was designed to avoid pessimizing code that has no need for it.

Upvotes: 10

Related Questions