Classes

C++ Inheritance

Class Inheritance

C++ inheritance uses : for base class extension.

Understanding C++ Inheritance

Inheritance is a fundamental concept in C++ that allows a class (known as a derived class) to inherit attributes and methods from another class (referred to as a base class). This mechanism promotes code reusability and establishes a hierarchical relationship between classes.

Defining a Base Class

Before we dive into inheritance, let's define a basic class that will serve as our base class. Consider the following example:

Extending a Base Class

To create a derived class, you use the colon : followed by an access specifier and the base class name. Here is an example of extending the Vehicle class:

Access Specifiers in Inheritance

When inheriting a class, the inherited members are affected by the access specifier used. The most common specifier is public, which maintains the original access levels of the base class members in the derived class.

  • Public Inheritance: Base class public and protected members remain public and protected in the derived class.
  • Protected Inheritance: Base class public and protected members become protected in the derived class.
  • Private Inheritance: Base class public and protected members become private in the derived class.

Using Derived Class

Once you have established the inheritance relationship, you can create objects of the derived class and access both the base class members and its own members:

Inheritance and Constructors

Constructors of the base class are not inherited by the derived class. However, the base class constructor is called when a derived class object is created. You can explicitly call base class constructors in the derived class constructor initializer list:

Previous
Classes