Re: Run-time type id and Inheritance

From: Shezan Baig (shezanbaig2004_at_gmail.com)
Date: 02/08/05


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-



Relevant Pages

  • Run-time type id and Inheritance
    ... Is there any possible way to determine if a class A inherits from class ... So if I have an Abstract Base Class called Grandparent, ... inherits from Parent called Child. ...
    (comp.lang.cpp)
  • Any Grandparents out there?
    ... fields: GP PP1 CC1 ... I basically want to have CC1+CC2+CC3+CC4 show up on the Grandparent ... textbox in the Child form and then in the Parent form using something ...
    (microsoft.public.access.formscoding)
  • Blocking virtual methods
    ... In pursuit of a child class blocking a parent's virtual method, ... : public Grandparent ... : public Parent ...
    (comp.lang.cpp)
  • Re: Any Grandparents out there?
    ... I realized that I could eliminate the parent ... altogether and get the total that directly from the child table to the ... grandparent table. ... >> footer textbox in child to bring it up to Grandparent? ...
    (microsoft.public.access.formscoding)
  • Re: How to call the grandparents method
    ... you only have access to your parent. ... exist in your grandparent definition. ... > I am Child ... > public virtual void WhoAmI() ...
    (microsoft.public.dotnet.languages.csharp)