Run-time type id and Inheritance

M

Michael H Lees

Is there any possible way to determine if a class A inherits from class
B at run-time.

So if I have an Abstract Base Class called Grandparent, then a class
which inherits from GrandParent called Parent and finally a class which
inherits from Parent called Child. Something like...

class GrandParent{
public:
virtual bool IsYoung(){return false;}
//...
};

class Parent : public GrandParent{
public:
// ...
};

class Child : public Parent{
public:
bool IsYoung(){return true;}
//...
};


GrandParent *gp_ptr;
Child c;

gp_ptr=&c;

is there anyway to determine that gp_ptr is now pointing to something
which inherits from Parent? Do I just attempt to cast the gp_ptr to a
Parent?

Thanks
 
S

Shezan Baig

Michael said:
Is there any possible way to determine if a class A inherits from class
B at run-time.

So if I have an Abstract Base Class called Grandparent, then a class
which inherits from GrandParent called Parent and finally a class which
inherits from Parent called Child. Something like...

class GrandParent{
public:
virtual bool IsYoung(){return false;}
//...
};

class Parent : public GrandParent{
public:
// ...
};

class Child : public Parent{
public:
bool IsYoung(){return true;}
//...
};


GrandParent *gp_ptr;
Child c;

gp_ptr=&c;

is there anyway to determine that gp_ptr is now pointing to something
which inherits from Parent? Do I just attempt to cast the gp_ptr to a

You can use a dynamic cast:

Parent* parentPtr = dynamic_cast<Parent*>(&c);
if (parentPtr) {
// yes, it is inherited from Parent
}
else {
// no, it is not
}


You need to make sure runtime type information is enabled on your
compiler for dynamic_cast to work correctly.

Hope this helps,
-shez-
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,201
Messages
2,571,048
Members
47,651
Latest member
VeraPiw932

Latest Threads

Top