Curriculum
Course: Learn C++
Login

Curriculum

Learn C++

Text lesson

Introduction to Inheritance in C++

In this lesson, you will learn

  • Inheritance
  • Types of Inheritance
  • Syntax of Inheritance

 

Introduction

Inheritance is one of the fundamental concepts in object-oriented programming (OOP) and is a key feature of the C++ programming language.

It allows you to create new classes that are based on existing classes, inheriting their properties and behaviors.

Inheritance promotes code reuse and is a crucial part of building complex, hierarchical class structures.

 

Terminology

Before diving into the details of inheritance, let’s clarify some essential terminology:

Base Class (Parent Class or Super Class): The class whose properties and behaviors are inherited by another class.

Derived Class (Child Class or Sub Class): The class that inherits properties and behaviors from a base class.

 

Types of Inheritance

In C++, there are several types of inheritance, each serving different purposes:

1. Single Inheritance

A derived class inherits from a single base class.

 

2. Multilevel Inheritance

A derived class is created from another derived class.

 

3. Multiple Inheritance

A derived class inherits from multiple base classes.

 

4. Hierarchical Inheritance

Multiple derived classes inherit from a single base class.

 

Hybrid Inheritance

A combination of different types of inheritance.

 

Syntax of Inheritance

The syntax for inheriting from a base class is as follows:

class BaseClass {
    // Base class members
};

class DerivedClass : access_specifier BaseClass {
    // Derived class members
};

 

access_specifier can be either public, protected, or private and determines the visibility of the base class members in the derived class.

 

Examples

1. Private derivation

class Derived: private Base //Private derivation
{
          // Members of derived class
}

 

In this case, the public member of a Base class becomes the private member of the Derived class.

Therefore public members of a Base class can only be accessed by the member functions of the Derived class. They are inaccessible to the object of the Derived class.

 

Note: The public members of a class can be accessed by its own object using the dot operator.

 

2. Public Derivation

class Derived: public Base //Public derivation
{
          // Members of derived class
}

 

In this case, the public member of a Base class becomes the public member of the Derived class and is accessible to the object of a Derived class.

 


 

End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review