Understanding Inheritance in C++

Lesson Introduction

Hello there! Welcome to our lesson on understanding inheritance in C++. Today, we're going to explore an important concept in programming called inheritance.

Why Inheritance?

Kids inherit certain traits from their parents, like eye color or hair color. In programming, inheritance works in a similar way. It allows one class (the child class) to inherit properties and behaviors from another class (the parent class). This helps us write more efficient and organized code by reusing existing code.

By the end of this lesson, you will understand what inheritance is in C++, how it works, and how to use it to create organized and reusable code.

Inheritance Syntax and Basic Example: part 1

In C++, we use the : symbol to indicate inheritance. For now, we'll use the public keyword to specify public inheritance. We'll discuss other inheritance options in the next lesson. Let's look at a basic example:

#include <iostream>

class Cat {
public:
    void voice() {
        std::cout << "Meow!" << std::endl;
    }
};

class Lion : public Cat {
};

class Tiger : public Cat {
};

In this example:

  • Cat is the base class.
  • Lion and Tiger are derived classes inheriting from Cat.
  • Both Lion and Tiger can use the voice() method from their parent class Cat.

Let's take a look at the main function example:

int main() {
    Cat cat;
    Lion lion;
    Tiger tiger;

    cat.voice();  // Output: Meow!
    lion.voice(); // Output: Meow!
    tiger.voice(); // Output: Meow!

    return 0;
}

In Lion and Tiger, we don't have to define the voice() method; they have it by default because they are inherited from the Cat class.

Inheritance Syntax and Basic Example: part 2

Let's add some attributes to our base class:

#include <iostream>

class Cat {
public:
    std::string color;
    int age;

    void voice() {
        std::cout << "Meow!" << std::endl;
    }
};

class Lion : public Cat {
};

class Tiger : public Cat {
};

Now, Cat is defined by its color and age. These attributes are also derived by the Lion and the Tiger classes.

Let's see how we can use them:

int main() {
    Lion lion;
    Tiger tiger;

    lion.color = "Golden";
    lion.age = 5;

    tiger.color = "Orange";
    tiger.age = 3;

    std::cout << "Lion: " << lion.color << ", " << lion.age << " years old" << std::endl; // Output: Lion: Golden, 5 years old
    std::cout << "Tiger: " << tiger.color << ", " << tiger.age << " years old" << std::endl; // Output: Tiger: Orange, 3 years old

    return 0;
}

Both Lion and Tiger can access the color and age attributes inherited from the Cat class.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal