Single Inheritance

MamtaWardhani's avatar
Published Feb 21, 2025
Contribute to Docs

Single inheritance is an Object-Oriented Programming (OOP) feature in which a class (derived class) inherits attributes and behaviors from a single base class. This allows code reuse, modular design, and the ability to extend the functionalities of existing classes.

Syntax

In C++, single inheritance follows this syntax:

class BaseClass {
  // Base class members
};

class DerivedClass : AccessSpecifier BaseClass {
  // Derived class members
};
  • BaseClass is the parent (superclass), containing common functionality.
  • DerivedClass inherits from BaseClass, gaining its attributes and methods.
  • AccessSpecifier (public, protected, or private) controls access to inherited members.

Example

In the following example, Car (derived class) inherits properties and methods from Vehicle (base class):

#include <iostream>
using namespace std;
class Vehicle {
public:
void startEngine() {
cout << "Engine started." << endl;
}
};
class Car : public Vehicle {
public:
void drive() {
cout << "Car is driving." << endl;
}
};
int main() {
Car myCar;
myCar.startEngine(); // Inherited from Vehicle
myCar.drive(); // Car's own method
return 0;
}

This produces the output as follows:

Engine started.
Car is driving.

In this example:

  • Car inherits the startEngine() method from Vehicle.
  • Car has its own method drive(), which extends the functionality.

Codebyte Example

Run the following example to understand how the single inheritance works:

Code
Output
Loading...

Note: The above code snippet uses the concept of Constructor Initialization Lists which is a common practice in C++ to call the base class constructor and initialize private data members.

All contributors

Contribute to Docs

Learn C++ on Codecademy