Using the pointer variables for class object instantiations and omitting the virtual keyword for C++ polymorphism 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 the use of pointer variables for class object instantiations and not using the virtual keyword for base class function C++ programming
To show:How to use the pointer variables for class object instantiations without the base class virtual function for C++ polymorphism programming
// C++ polymorphism not using the virtual function example
#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 class, 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()
};
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)
{
// All pointer variables here
vehicle *unicycle;
car *sedan_car;
truck *trailer;
boat *sailboat;
cout<<"Omitting the virtual keyword. Using pointer variables, and new keyword for C++ polymorphism,"<<endl;
cout<<"derived/inherited class function/method can't override the base class function/method"<<endl;
cout<<"---------------------------------------------------------------------------------------------"<<endl;
unicycle = new vehicle;
unicycle->message();
sedan_car = new car;
sedan_car->message();
trailer = new truck;
trailer->message();
sailboat = new boat;
sailboat->message();
unicycle = sedan_car;
unicycle->message();
return 0;
}
Output example:
Omitting the virtual keyword. Using pointer variables, and new keyword for C++ polymorphism,
derived/inherited class function/method can't override the base class function/method
---------------------------------------------------------------------------------------------
Vehicle message() from vehicle class, the base class
Car message() from car class, the vehicle derived class
Vehicle message() from vehicle class, the base class
Boat message() from boat class, the vehicle derived class
Vehicle message() from vehicle class, the base class
Press any key to continue . . .