By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,798 Members | 1,766 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,798 IT Pros & Developers. It's quick & easy.

Run-time type id and Inheritance

P: n/a
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

Jul 23 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a

Michael H Lees wrote:
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?


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-

Jul 23 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.