Inheritance in C++

Here is an example of how the Vehicle example could look in C++. This code is simplified and wouldn't pass a compiler, but it gives an idea of how a class, encapsulation, attributes, operations and inheritance are implemented.

class Vehicle
{
public:
vehicle();
~vehicle();
move();
stop();
private:
int weight;
int speed=0;
};
The first operation, vehicle(), is called "constructor" and is the method that can create a new instances of the class Vehicle. This method allocates memory and initiates the attributes. The operation ~vehicle() is the "destructor" which takes care of the liquidation of an object, i.e. deallocation of the memory held by the object.

In C++, "public" and "private" defines accessability of operations and data. Operations accessible to other objects are defined under "public", while data and operations "for internal use only" are encapsulated under "private".

Class Car is a Subclass of Class Vehicle

class Car : Vehicle
{
public:
car();
~car();
toot();
shift_gear();
private:
char *reg_no;
gear {N,G1,G2,G3,G4,G5,R};
}
Here there are two additional operations toot and shift_gear and the attributes reg_no and gear (which stores the current gear).

If we later on find out that we have to distinguish between different kinds of Cars, let's say SportsCars, Lorries and Buses, we can add a new level in our inheritance hierarchy and let the classes SportsCar, Lorry and Bus inherit the class Car.


previous | next | start | contents | dictionary | help | evaluation

© Ericsson Telecom AB, 1995, Stockholm, Sweden