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

Discussion in 'C++' started by Titan, Jun 30, 2003.

  1. Titan

    Titan Guest

    Hi all,

    In Delphi the following code will work:
    (xx[n-1]as TLibr).XEarth=xx[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,
     
    Titan, Jun 30, 2003
    #1
    1. Advertising

  2. Titan

    tom_usenet Guest

    On 30 Jun 2003 02:05:37 -0700, (Titan) wrote:

    >Hi all,
    >
    >In Delphi the following code will work:
    >(xx[n-1]as TLibr).XEarth=xx[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++ ?


    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<TLibr&>(*(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
     
    tom_usenet, Jun 30, 2003
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jonas
    Replies:
    1
    Views:
    392
    S. Justin Gengo
    Aug 12, 2003
  2. qazmlp
    Replies:
    7
    Views:
    492
    Howard
    Jul 27, 2004
  3. Ninereeds
    Replies:
    2
    Views:
    300
    Ninereeds
    Apr 3, 2007
  4. Replies:
    1
    Views:
    396
    myork
    May 23, 2007
  5. Replies:
    1
    Views:
    389
    Victor Bazarov
    May 23, 2007
Loading...

Share This Page