Skip to main content
eLearner.app
Module 6 · Lesson 1 of 213/18 in the course~12 min
Module lessons (1/2)

Inheritance in C++

Inheritance is one of the key pillars of Object-Oriented Programming (OOP). It allows a new class (called the derived or child class) to inherit members (attributes and methods) from an existing class (called the base or parent class), promoting code reuse.

Basic Syntax

In C++, inheritance is specified using the : operator after the derived class name, followed by an access specifier (usually public) and the base class name.

Code
class Shape {
public:
    void setColor(std::string c) {
        color = c;
    }
protected:
    std::string color; // Accessible by derived classes
};

// Rectangle inherits publicly from Shape
class Rectangle : public Shape {
public:
    double getArea() {
        return width * height;
    }
private:
    double width {0.0};
    double height {0.0};
};

Access Specifier: protected

Along with public and private, inheritance introduces the protected specifier:

  • private members of the base class are not directly accessible from the derived class.
  • protected members of the base class are inaccessible from the outside, but are directly accessible inside derived classes.

Base Class Initialization

Constructors are not automatically inherited. When instantiating a derived class, the base class constructor is called first. If the base class requires arguments, we must invoke it explicitly in the member initializer list of the derived constructor.

Code
class Parent {
public:
    Parent(int x) {
        std::cout << "Parent: " << x << std::endl;
    }
};

class Child : public Parent {
public:
    // Explicit call to Parent constructor
    Child(int x, int y) : Parent(x) {
        std::cout << "Child: " << y << std::endl;
    }
};

Try it yourself

Exercise#cpp.m6.l1.e1
Attempts: 0Loading…

Create a Dog class that publicly inherits from the Animal class. The Dog class must include a public play() method that prints 'Playing' using std::cout.

Loading editor…
Show hint

Use the `:` syntax followed by `public Animal` to extend the base class, then write the `play()` method.

Solution available after 3 attempts

Exercise#cpp.m6.l1.e2
Attempts: 0Loading…

Complete the Car class by inheriting from Vehicle. Write a constructor for Car that accepts std::string b and passes it to the Vehicle constructor via the member initializer list.

Loading editor…
Show hint

In the `Car` constructor, use the syntax `: Vehicle(b)` immediately after the parameter parentheses to delegate the initialization of brand to the base class.

Solution available after 3 attempts