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:
In this example:
Catis the base class.LionandTigerare derived classes inheriting fromCat.- Both
LionandTigercan use thevoice()method from their parent classCat.
Let's take a look at the main function example:
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:
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:
Both Lion and Tiger can access the color and age attributes inherited from the Cat class.
