Re: Run-time type id and Inheritance
From: Shezan Baig (shezanbaig2004_at_gmail.com)
Date: 02/08/05
- Next message: Stavros Christoforou: "Random numbers within a sphere?"
- Previous message: lmo863: "matlab into c++"
- In reply to: Michael H Lees: "Run-time type id and Inheritance"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 8 Feb 2005 05:50:22 -0800
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-
- Next message: Stavros Christoforou: "Random numbers within a sphere?"
- Previous message: lmo863: "matlab into c++"
- In reply to: Michael H Lees: "Run-time type id and Inheritance"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|