The classes ADC and MCA are derived from Detector which is derived from
Device. Upcasting occurs in this line det = &adc
, which allows the
ADC to be treated as a Detector and upcasting occurs also by the function
display( Detector *det)
which is later fed by an ADC and a MCA. This
is possible because both are detectors.
// // g++ upcasting.cpp // #include <iostream> using namespace std; class Device { public: Device( string name) { Name = name; } string Name; }; class Detector:public Device { public: Detector(string name, string nDim) : Device( name) { NDim = nDim; } string NDim; void show() { cout << Name << " is a " << NDim << " device" << endl; } }; class ADC :public Detector { public: ADC(string name, string nDim, double offset) : Detector( name, nDim) { Offset = offset; } double Offset; double getOffset() { return Offset; } }; class MCA :public Detector { public: MCA(string name, string nDim, int channels) : Detector( name, nDim) { Channels = channels; } int Channels; int getChannels() { return Channels; } }; void display( Detector* det) { cout << "Display a detector" << endl; det->show(); }; int main() { Detector* det; // objects derived from Detector ADC adc( "adc1", "0D", 123); MCA mca( "mca1", "1D", 1024); // upcasting det = &adc; // the base class has Name and NDim cout << det->Name << " nDim " << det->NDim << endl; // Fails because Detector has no getChannels() // cout<< det->getChannels(); display( &adc); display( &mca); }