The C++ polymorphism: assigning the derived (inherited) class object to the base class object code sample

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Displaying some data to demonstrate how to assign the derived (inherited) class object to the base class object in C++ programming

To show: How to assign the derived (inherited) class object to the base class object in C++ programming

 

 

// the C++ polymorphism, derived (inherited) and base class object assignment

#include <iostream>

using namespace std;

 

// base class declaration and implementation

class vehicle

{

int wheels;

float weight;

public:

// first message()

void message(void)

{

cout<<"Vehicle message() from vehicle, the base class"<<endl;

}

};

 

// derived class declarations and implementations

class car : public vehicle

{

int passenger_load;

public:

// second message()

void message(void)

{

cout<<"Car message() from car class, the vehicle derived class"<<endl;

}

};

 

class truck : public vehicle

{

int passenger_load;

float payload;

public:

int passengers(void)

{

return passenger_load;

}

// no message(), will use the base class version

};

 

class boat : public vehicle

{

int passenger_load;

public:

int passengers(void)

{

return passenger_load;

}

// third message()

void message(void)

{

cout<<"Boat message() from boat class, the vehicle derived class"<<endl;

}

};

 

// the main program

int main(void)

{

vehicle unicycle;

car sedan_car;

truck trailer;

boat sailboat;

 

unicycle.message();

sedan_car.message();

trailer.message();

sailboat.message();

 

// base and derived objects assignment

cout<<endl;

cout<<"The derived (inherited) class object assigned to the base class object"<<endl;

unicycle = sedan_car;

unicycle.message();

return 0;

}

 

Output example:

 

Vehicle message() from vehicle, the base class

Car message() from car class, the vehicle derived class

Vehicle message() from vehicle, the base class

Boat message() from boat class, the vehicle derived class

The derived (inherited) class object assigned to the base class object

Vehicle message() from vehicle, the base class

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index