tags:

views:

165

answers:

3

Hi all,

all the while, I am using dynamic_cast to determine Parent-Child relationship of an object.

#include <iostream>

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

class B : public A {
};

class C : public A {
};

int main()
{
    B b;
    std::cout<< typeid(b).name()<< std::endl;       // class B

    A* a = dynamic_cast<A *>(&b);
    if (a) {
        std::cout<< "is child of A"<< std::endl;    // printed
    }

    C* c = dynamic_cast<C *>(&b);
    if (c) {
        std::cout<< "is child of C"<< std::endl;    // Not printed
    }
    getchar();
}

May I know is it possible that I can determine parent-child relationship, of an object, through typeid? For example, how I can know B is the child of A, by using typeid checking?

Thanks.

+4  A: 

I don't think you can do that in current C++ using the information in typeinfo only. I know of boost::is_base_of (Type Traits will be part of C++0x):

if ( boost::is_base_of<A, B>::value ) // true
{
    std::cout << "A is a base of B";
}
AraK
http://www.boost.org/doc/libs/release/libs/type_traits/doc/html/boost_typetraits/reference/is_base_of.html
Roger Pate
A: 

You could just google something like c++ typeid example and get something like this back: http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/the%5Ftypeid%5Foperator.htm

:)

Gyuri
or even http://en.wikipedia.org/wiki/Typeid
Gyuri
A: 

typeid is opaque. It is not meant to be a form of reflection. That said, doing a null check on the return from dynamic_cast is probably just as fast trying to traverse typeid structures to determine class relationships. Stick with dynamic_cast in pre-C++0x code.

jmucchiello