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

T

Titan

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,
 
T

tom_usenet

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top