C++ Single Inheritance
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
};
BaseClassis the parent (superclass), containing common functionality.DerivedClassinherits fromBaseClass, gaining its attributes and methods.AccessSpecifier(public,protected, orprivate) 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 VehiclemyCar.drive(); // Car's own methodreturn 0;}
This produces the output as follows:
Engine started.Car is driving.
In this example:
Carinherits thestartEngine()method fromVehicle.Carhas its own methoddrive(), which extends the functionality.
Codebyte Example
Run the following example to understand how the single inheritance works:
Note: The above code snippet uses the concept of
Constructor Initialization Listswhich is a common practice in C++ to call the base class constructor and initialize private data members.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours