0% found this document useful (0 votes)
15 views15 pages

C++ Inheritance: Types and Syntax Explained

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views15 pages

C++ Inheritance: Types and Syntax Explained

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

What Is Inheritance In C++?

- Inheritance in C++ language is a core concept of object-orientedoriented programming (OOP)


that allows you to create new classes (derived classes
classes/child classes/subclasses
/subclasses) based on
existing classes (base classes
classes/parentclasses/superclasses).
- When we say derived class inherits the base class class, it means that the derived class
inherits all the properties of the base class, without changing the properties of base
class and may add new features to its own. These new features in the derived class will
not affect the base class. The derived class is the specialized class for the base class.
- The main purpose of Inheritance is to increase code reusability
reusability.

Why do we use Inheritance? A An example.


Let’s understand the need of inheritance with the help of an example. Consider a group of
vehicles. You need to create classes for Bus, Car, and Truck. The methods fuelAmount(),
capacity(), applyBrakes() will be the same for all three classes. If we create these classes
without inheritance, then we have to write all of these functions in each of the three classes as
shown below figure:

- Clearly, this results in duplication of the same code 3 times. This increases the chances
of error and data redundancy.
- To avoid this type of situation, inheritance is used. If we create a class Vehicle and
write these three functions in it and inherit these from the vehicle
ehicle class, then we can
simply avoid the duplication of data and increase rere-usability. This is explained in the
below diagram.

- Using inheritance, we have to write the functions only one time instead of three times
as we have inherited the rest of the three classes from the base class (Vehicle).
Child Class/Derived Class/Sub Class:
- The class that inherits properties from another class.

Parent Class/Base Class/Super Class:


- The class whose properties are inherited by a subclass.

Syntax of Inheritance In C++


- It contains a child class (which inherits the attributes and methods) and a parent class.
- The syntax for defining a parent and child class in all types of inheritance in C++ is
explained below.

class ParentClassName
{
// parent class definition
};

class ChildClassName : visibility_mode ParentClassName


{
// child class definition
};

Here,
- class: It is the keyword for creating a new class.
- ParentClassName: It is the name of the base class/parent class.
- ChildClassName: It is the name of the derived class/child class.
- Visibility_mode: It is the access specifier that determines how inherited members
are visible in the derived class (public, protected, or private).
- If neither visibility mode is specified, it takes private as the default mode.
- Private members of the base class never get inherited by the child class.
- If the public members of the base class are privately inherited by the child class,
then they become the private members of the child class.

C++ Code Example:

class Parent // Base class


{ public:
int id_p;
void printID_p()
{
cout << "Base ID: " << id_p << endl;
}
};

class Child : public Parent // Derived publicly inheriting from Base Class
{ public:
int id_c;
void printID_c()
{
cout << "Child ID: " << id_c << endl;
}
};

int main()
{
Child obj1;
obj1.id_p = 7;
obj1.printID_p();

obj1.id_c = 91;
obj1.printID_c();
return 0;
}

Output:
Base ID: 7
Child ID: 91

Modes of Inheritance in C++


Mode of inheritance controls the access level of the inherited members of the base class in the
derived class. In C++, there are 3 modes of inheritance:
- Public Mode
- Protected Mode
- Private Mode

Public Inheritance Mode


- If we derive a subclass from a public base class, then the public member of the base
class will become public in the derived class and protected members of the base class
will become protected in the derived class.

Example:
class ABC : public XYZ {...}; // public derivation

Protected Inheritance Mode


- If we derive a subclass from a protected base class, then both public members and
protected members of the base class will become protected in the derived class.
Example:
class ABC : protected XYZ {...}; // protected derivation

Private Inheritance Mode


- If we derive a subclass from a Private base class, then both public members and
protected members of the base class will become private in the derived class.
- Private mode is the default mode that is applied when we don’t specify any mode.
- The private members in the base class cannot be directly accessed in the derived
class, while protected and public members can be directly accessed.

Example:
class ABC : private XYZ {...} // private derivation or
class ABC: XYZ {...} // private derivation by default

The below table summarizes the above three modes and shows the access specifier of the
members of the base class in the subclass when derived in public, protected and private modes:

Examples of Modes of Inheritance


Program to show different kinds of Inheritance Modes and their Member Access Levels

class A // Base class


{ public:
int x;
protected:
int y;
private:
int z;
};

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
};

The above program shows that private members of the base class remain encapsulated. We can
also access the private members of the base class by declaring the derived class as friend class
in the base class.

Types of Inheritance in C++


The inheritance can be classified on the basis of the relationship between the derived class and
the base class. In C++, we have 5 types of inheritances:
- Single inheritance
- Multiple inheritance
- Multilevel inheritance
- Hierarchical inheritance
- Hybrid inheritance

Single Inheritance
In single inheritance, a class is allowed to inherit from only one class. i.e. one base class is
inherited by one derived class only.

Syntax:
class subclass_name : access_mode base_class
{
// body of subclass
};
Example:

class A
{
... .. ...
};
class B: public A
{
... .. ...
};

C++ code example:

class Vehicle // base class


{ public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};

class Car : public Vehicle // derived class


{ public:
Car()
{
cout << "This Vehicle is a Car\n";
}
};

int main()
{
Car obj;
return 0;
}

Output:
This is a Vehicle
This Vehicle is a Car

Multiple Inheritance
In multiple inheritance a class can inherit from more than one class.
Syntax:
class subclass_name : access_mode base_class1, access_mode base_class2, ....
{
// body of subclass
};

Here, the number of base classes will be separated by a comma (‘, ‘) and the access mode for
every base class must be specified and can be different.

Example:

class A
{
... .. ...
};
class B
{
... .. ...
};
class C: public A, public B
{
... ... ...
};

C++ Code Implementation:

class Vehicle // first base class


{ public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};

class FourWheeler { // second base class


{ public:
FourWheeler()
{
cout << "This is a 4 Wheeler\n";
}
};

class Car : public Vehicle, public FourWheeler // sub class derived from two base classes
{ public:
Car()
{
cout << "This 4 Wheeler Vehical is a Car\n";
}
};

int main()
{
Car obj;
return 0;
}
Output:
This is a Vehicle
This is a 4 Wheeler
This 4 Wheeler Vehical is a Car

Multilevel Inheritance
In this type of inheritance, a derived class is created from another derived class and that
derived class can be derived from a base class or any other derived class. There can be any
number of levels.

Syntax:
class derived_class1: access_specifier base_class
{
... .. ...
}
class derived_class2: access_specifier derived_class1
{
... .. ...
}
.....

Example:
class A
{
... .. ...
};
class B : public A
{
... .. ...
};
class C: public B
{
... ... ...
};
C++ Code Implementation:

class Vehicle // base class


{ public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};

class fourWheeler : public Vehicle // sub_class derived from base class vehicle
{ public:
fourWheeler()
{
cout << "4 Wheeler Vehicles\n";
}
};

class Car : public fourWheeler // sub class derived from the derived class fourWheeler
{ public:
Car()
{
cout << "This 4 Wheeler Vehical is a Car\n";
}
};

int main()
{
Car obj;
return 0;
}

Output:
This is a Vehicle
4 Wheeler Vehicles
This 4 Wheeler Vehical is a Car

Hierarchical Inheritance
In this type of inheritance, more than one derived class is created from a single base class.

Syntax
class derived_class1: access_specifier base_class
{
... .. ...
}
class derived_class2: access_specifier base_class

{
... .. ...

Example:
class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D
}

C++ Code Implementation:

class Vehicle // base class


{ public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};

class Car : public Vehicle { // first sub class


{ public:
Car()
{
cout << "This Vehicle is Car\n";
}
};

class Bus : public Vehicle { // second sub class


{ public:
Bus()
{
cout << "This Vehicle is Bus\n";
}
};

int main()
{
Car obj1;
Bus obj2;
return 0;
}

Output:
This is a Vehicle
This Vehicle is Car
This is a Vehicle
This Vehicle is Bus

Hybrid Inheritance
- Hybrid Inheritance is implemented by combining more than one type of inheritance.
For example: Combining Hierarchical inheritance and Multiple Inheritance will
create hybrid inheritance in C++
- There is no particular syntax of hybrid inheritance. We can just combine two of the
above inheritance types.

Example:
Below image shows one of the combinations of hierarchical and multiple inheritances:
class F
{
... .. ...
};
class G
{
... .. ...
};
class B : public F
{
... .. ...
};
class E : public F, public G
{
... .. ...
};
class A : public B
{
... .. ...
};

class C : public B
{
... .. ...
};

C++ Code Implementation:


class Vehicle // base class
{ public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};

class Fare // base class


{ public:
Fare()
{
cout << "Fare of Vehicle\n";
}
};

class Car : public Vehicle // first sub class


{ public:
Car()
{
cout << "This Vehical is a Car\n";
}
};

class Bus : public Vehicle, public Fare // second sub class


{ public:
Bus()
{
cout << "This Vehicle is a Bus with Fare\n";
}
};

int main()
{
Bus obj2;
return 0;
}

Output:
This is a Vehicle
Fare of Vehicle
This Vehicle is a Bus with Fare

What is a virtual base class?


A problem, known as diamond problem can arise when several paths exist to a class from the
same base class. This means that a child class could have duplicate sets of members inherited
from a single base class. C++ solves this issue by introducing a virtual base class. When a class
is made virtual, necessary care is taken so that the duplication is avoided regardless of the
number of paths that exist to the child clas
class

Need for Virtual Base Classes:


Consider the situation where we have one class A . This class A is inherited by two other
classes B and C. Both these class are inherited into another in a new class D as shown in figure
above.

As we can see from the figure that data members/function of class A are inherited twice to
class D. One through class B and second through class C. When any data / function member of
class A is accessed by an object of class D, ambiguity arises as to which data/function member
would be called? One inherited through B or the other inherited through C. C This confuses
compiler and it displays error.

C++ code example:


class A {
{ public:
void show()
{
cout << "Hello from A \n";
}
};
class B : public A
{
};
class C : public A
{
};
class D : public B, public C
{
};

int main()
{
D object;
[Link]();
}

Output: Compile Errors

How to resolve this issue?


- To resolve this ambiguity when class A is inherited in both class B and class C, it is
declared as virtual base class.
- A single copy of data members is shared by all the base classes that use virtual base.

Syntax for Virtual Base Classes:


Syntax 1:
class B : virtual public A
{
};

Syntax 2:
class C : public virtual A
{
};

C++ Code:
class A
{ public:
int a;
A() // constructor
{
a = 10;
}
};

class B : public virtual A


{
};

class C : public virtual A


{
};
class D : public B, public C
{
};

int main()
{
D object;
cout << "a = " << object.a << endl;

return 0;
}

Output: a = 10

Diamond Problem in C++


- The diamond problem occurs in C++ during multiple inheritance when two or more
parent classes of a derived class have a common base class. This situation creates
ambiguity because the compiler cannot determine which ancestor's features to inherit if
the same feature exists in more than one ancestor.

You might also like