How to access data or functions of the derived class if it was declared as the base class?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Titan

    How to access data or functions of the derived class if it was declared as the base class?

    Hi all,

    In Delphi the following code will work:
    (xx[n-1]as TLibr).XEarth=x x[1].xm*(-1.0);
    where xx is defined as a array of class TBody, and it has n members;
    Tlibr is the derived class of Tbody, and Xearth is its private data.

    How to write the corresponding code in c++ ?

    Thanks,
  • tom_usenet

    #2
    Re: How to access data or functions of the derived class if it was declared as the base class?

    On 30 Jun 2003 02:05:37 -0700, amaths@sohu.com (Titan) wrote:
    [color=blue]
    >Hi all,
    >
    >In Delphi the following code will work:
    >(xx[n-1]as TLibr).XEarth=x x[1].xm*(-1.0);
    >where xx is defined as a array of class TBody, and it has n members;
    >Tlibr is the derived class of Tbody, and Xearth is its private data.
    >
    >How to write the corresponding code in c++ ?[/color]

    If Xearth is private, you can't access it. It it isn't private, then,
    firstly you'll need an array of TBody* rather than TBody (an array of
    TBody only contains TBody elements, and not elements derived from
    TBody), and secondly the code should look something like this:

    The set up code looks something like this:
    TBody* xx[n]; //or TBody** xx = new TBody*[n];
    xx[n-1] = new TLibr;


    and here's the transcription of your code:
    dynamic_cast<TL ibr&>(*(xx[n-1])).XEarth = xx[1]->xm * -1.0;

    It will throw an exception if xx[n-1] isn't an instance of TLibr.

    Tom

    Comment

    Working...