In this tutorial, we will learn about the inheritance in C++, its important and use with detailed example.
Acquiring the properties of parent class to sub class objects is called Inheritance”
Concept of Inheritance
Base Classes and Derived Classes
In above diagram, Car is Base class where as pickup truck and truck class is dervied class. Inhertance allows to construct new classes by inheriting property of exixting class. In this process the new derived class inherits the data and methods of base class.
Pickup Truck object is a special kind of car it has all the feature of a car and additionally it has its own unique feature and same with the truck.
Types of inheritance in C++
- single inheritance
- multilevel inheritance
- hierarchical inheritance
- multiple inheritance
- hybrid inheritance
C++ Inheritance Syntax or Format
class derived_class_name : acess_specifier base_class_name
Private keywords are the visibility labels in
If no modifier then it is
private by default.
Importance of inheritance
There are many benefits of using inheritance in software development.
General properties can be defined in base class and only special properties can be organized in a relationship using derived classes. All the features of car will be in base class Car and for the special properties of pickup truck, it will be defined in the pickup truck itself.
Class that are already defined and tested can be reused for performing new task.
Implementation of Inheritance in C++
class B : public A
// x is public
// y is protected
// z is not accessible from B
class C : protected A
// x is protected
// y is protected
// z is not accessible from C
class D : private A // 'private' is default for classes
// x is private
// y is private
// z is not accessible from D