C++ Tutorial on inheritance


Creating or deriving a new class using another class as a base is called inheritance in C++. The new class created is called a Derived class and the old class used as a base is called a Base class in C++ inheritance terminology.

The derived class will inherit all the features of the base class in C++ inheritance. The derived class can also add its own features, data etc., It can also override some of the features (functions) of the base class, if the function is declared as virtual in base class.

C++ inheritance is very similar to a parent-child relationship. When a class is inherited all the functions and data member are inherited, although not all of them will be accessible by the member functions of the derived class. But there are some exceptions to it too.

Some of the exceptions to be noted in C++ inheritance are as follows.

  • The constructor and destructor of a base class are not inherited
  • the assignment operator is not inherited
  • the friend functions and friend classes of the base class are also not inherited.

There are some points to be remembered about C++ inheritance. The protected and public variables or members of the base class are all accessible in the derived class. But a private member variable not accessible by a derived class.

It is a well known fact that the private and protected members are not accessible outside the class. But a derived class is given access to protected members of the base class.

Let us see a piece of sample code for C++ inheritance. The sample code considers a class named vehicle with two properties to it, namely color and the number of wheels. A vehicle is a generic term and it can later be extended to any moving vehicles like car, bike, bus etc.,

class vehicle //Sample base class for c++ inheritance tutorial
{
protected:
char colorname[20];
int number_of_wheels;
public:
vehicle();
~vehicle();
void start();
void stop();
void run();
};
class Car: public vehicle //Sample derived class for C++ inheritance tutorial
{
protected:
char type_of_fuel;
public:
Car();
};

The derived class Car will have access to the protected members of the base class. It can also use the functions start, stop and run provided the functionalities remain the same.

In case the derived class needs some different functionalities for the same functions start, stop and run, then the base class should implement the concept of virtual functions.