The C++ class inheritance: A simple C++ project development process
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 creating simple C++ object oriented project development process
To show: How to implement the C++ object oriented class inheritance in C++ programming properly
Create a new Win32 console mode application project named vehicleobject. Add the following header file to your project, named vehicle.h. No need to be compiled.
// the class declaration part, vehicle.h, header file
// add vehicle.h header file to your project, paste the code and save it, do not compile or run
//
// preprocessor directive to avoid the
// similar header file re-inclusion
#ifndef VEHICLE_H
#define VEHICLE_H
// class declaration
class Cvehicle
{
// a protected class member can only be accessed or inherited by Cvehicle child or derived class
protected:
int wheels;
float weight;
public:
void initialize(int input_wheels,float input_weight);
int get_wheels(void);
float get_weight(void);
float wheel_load (void);
};
#endif
Next add another source file for the class implementation part named vehicle.cpp. Compile it.
// program vehicle.cpp, implementation part, compile without error, generating object file, do not run
#include "vehicle.h"
// class implementation
// initialize to the initial data
void Cvehicle::initialize(int input_wheels, float input_weight)
{
wheels = input_wheels;
weight = input_weight;
}
// get the number of wheels of this vehicle
int Cvehicle::get_wheels()
{
return wheels;
}
// return the weight of this vehicle
float Cvehicle::get_weight()
{
return weight;
}
// return the load on each wheel
float Cvehicle::wheel_load()
{
return (weight/wheels);
}
Finally add and run the main() program, myvehicle.cpp
#include <iostream>
using namespace std;
// user define header file and put it in the same folder or project
#include "vehicle.h"
void main(void)
{
// 4 objects instantiated of type Cvehicle class
Cvehicle car, motorcycle, truck, sedan_car;
// data initialization
car.initialize(4,3000.0);
truck.initialize(20,30000.0);
motorcycle.initialize(2,900.0);
sedan_car.initialize(4,3000.0);
// display the data
cout<<"The car has "<<car.get_wheels()<< " tyres."<<endl;
cout<<"Truck has load "<<truck.wheel_load()<<" kg per tyre."<<endl;
cout<<"Motorcycle weight is "<<motorcycle.get_weight()<<" kg."<<endl;
cout<<"Weight of sedan car is "<<sedan_car.get_weight()<<" kg, and has "<<sedan_car.get_wheels()<<" tyres."<<endl;
return;
}
Output example:
The car has 4 tyres.
Truck has load 1500 kg per tyre.
Motorcycle weight is 900 kg.
Weight of sedan car is 3000 kg, and has 4 tyres.
Press any key to continue . . .