next up previous
Next: About this document ... Up: Overview of C++ Previous: Activity

Inheritance

C++ supports inheritance by allowing one class to incorporate another class into its declaration. The following class called road_vehicle, defines very broadly vehicles that travel on the road. It stores the number of wheels a vehicle has and the number of passengers it can carry.

Example
#include<iostream.h>

class road_vehicle{
int wheels;
int passengers;
public:
void set_wheels(int num){ wheels=num;}
int get_wheels(){return wheels;}
void set_pass(int num){passengers=num;}
int get_pass(){return passengers;}
};
class truck :public road_vehicle {
int cargo;
public:
void set_cargo(int size){cargo=size;}
int get_cargo(){ return cargo;}
void show();
};
enum type car, van,wagon; // this is a key word define a list of named integer constants 0=car, 1=van and 2=wagon)
class automobile :public road_vehicle{
enum type car_type; public: set_type(type t){car_type=t;}
enum type get_type() {return car_type;}
};
void truck::show()
{
cout << wheels:"<<get_wheels()<<"$\backslash$n";
cout <<"passengers: "<<get_pass() <<"$\backslash$n";
cout <<"cargo capacity in cubic feet "<<cargo << "$\backslash$n";
}
void automobile::show()
{
cout << wheels:"<<get_wheels()<<"$\backslash$n";
cout <<"passengers: "<<get_pass() <<"$\backslash$n";
cout <<"type:"; switch(get_type()){
case van:cout <<"van$\backslash$n";
break; case car:cout <<"car$\backslash$n";
break; case wagon:cout <<"wagon$\backslash$n";
}
}
main()
truck t1, t2;
automobile c;
t1.set_wheels(18);
t1.set_pass(2);
t1.set_cargo(3200);

t2.set_wheels(6);
t2.set_pass(3);
t2.set_cargo(1200);

t1.show();
t2.show();

c.set_wheels(4);
c.set_pass(6);
c.set_type(van);
c.show();
return 0;
}



Yousef Haik
2/23/1998