DEV Community

dinhluanbmt
dinhluanbmt

Posted on

c++, check object class type

In C++, we can check the type of an object at runtime using the typeid operator or the dynamic_cast operator.

#include <iostream>
#include <typeinfo> // for typeid 
using namespace std;
class Base {
public:
    virtual ~Base() {}
};
class Derived : public Base {
};
int main() {
    Base* basePtr = new Derived();
    if (typeid(*basePtr) == typeid(Derived)) {
        cout << "basePtr is an instance of Derived class" <<endl;
    } else {
        cout << "basePtr is not ..." <<endl;
    }
    delete basePtr;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

or dynamic_cast

#include <iostream>
using namespace std;
class Base {
public:
    virtual ~Base() {}
};
class Derived : public Base {
};
int main() {
    Base* basePtr = new Derived();
    if (Derived* d_ptr = dynamic_cast<Derived*>(basePtr)) {
        cout << "basePtr is an instance of Derived class" <<endl;
    } else {
        cout << "basePtr is not ..." <<endl;
    }
    delete basePtr;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (6)

Collapse
 
pauljlucas profile image
Paul J. Lucas

You neglected to mention that this works only if the object is a class that has at least one virtual member function.

Collapse
 
dinhluanbmt profile image
dinhluanbmt

actually, i did not know about that, because every time i define Base class, i used at least virtual destructor in order to enable destructor of Derived class

Collapse
 
pauljlucas profile image
Paul J. Lucas

Not every base class needs virtual functions or destructors. If their typical use is to be used directly (not via a pointer to reference to the base class), then adding virtual (1) bloats the object by adding sizeof(void*) to it and (2) requires a virtual function call for the destructor (at least) that, if there are lots of such objects or they're created/destroyed in tight loops, is a real performance hit.

Thread Thread
 
dinhluanbmt profile image
dinhluanbmt

could you explain more ? if we use Base class directly, do we need to define Derived class ?

Thread Thread
 
pauljlucas profile image
Paul J. Lucas

Your question makes no sense. If you don't need any particular class (derived or not), then don't define it.

An example of what I'm talking about is if you did something like:

class my_string : public std::string {
    // ...
};
Enter fullscreen mode Exit fullscreen mode

and you add a custom member function. In your code, you only ever use my_string, my_string*, and my_string&. In particular, you never do:

my_string *pms;
// ...
std::string *pss = pms;
// ...
delete pss; // If you never do this, ...
Enter fullscreen mode Exit fullscreen mode

then the fact that the destructor of std::string is not virtual doesn't matter because you never use my_string polymorphically.

Thread Thread
 
dinhluanbmt profile image
dinhluanbmt

I got it, sorry because I just focus on polymorphism