C++ polymorphism on how to use the non-pointer variables to instantiate objects and the use of base class virtual function for overriding the base class function by derived (inherited) function with similar signature
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 the use of the non-pointer variables for object instantiations and the virtual function in the C++ programming
To show:How to use the non-pointer variables for object instantiations and the base class virtual function for derived (inherited) function overriding in C++ programming
// using non-pointer variables for the object instantiation and the virtual keyword
#include <iostream>
using namespace std;
// base class declaration and implementation
class vehicle
{
int wheels;
float weight;
public:
// note the virtual keyword
// derived (inherited) class /method function with similar signature will override this base class message() function
virtual void message(void)
{
cout<<"Vehicle message(), 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() function/method
};
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)
{
// non-pointer object variables
vehicle unicycle;
car sedan_car;
truck trailer;
boat sailboat;
cout<<"Adding the virtual keyword for the base class function/method,"<<endl;
cout<<"non-pointer variables use. The basic use of the virtual function/method"<<endl;
cout<<"in C++ programming"<<endl;
cout<<"------------------------------------------------------------------------"<<endl;
unicycle.message();
sedan_car.message();
trailer.message();
sailboat.message();
// unicycle = sedan_car;
// sedan_car.message();
return 0;
}
Output example:
Adding the virtual keyword for the base class function/method,
non-pointer variables use. The basic use of the virtual function/method
in C++ programming
------------------------------------------------------------------------
Vehicle message(), the base class
Car message() from car class, the vehicle derived class
Vehicle message(), the base class
Boat message(), from boat class, the vehicle derived class
Press any key to continue . . .