Inheritance in C++
Inheritance in C++
Welcome back! Now that you have a solid understanding of classes and objects in C++, it's time to build on that knowledge by exploring inheritance. Consider it a natural progression in our journey into object-oriented programming (OOP).
Inheritance allows you to create a new class based on an existing class. By using inheritance, you can reuse code, add new features, and make your programs easier to manage and understand. Let's dive in and see what it's all about.
What You'll Learn
In this lesson, you'll understand how to use inheritance in C++. We'll cover:
- What Inheritance Is
- How to Implement Inheritance in C++
- Why Inheritance Is Beneficial
What Inheritance Is
Inheritance is a way to establish a relationship between a new class (derived class) and an existing class (base class). The derived class inherits properties and behaviors (methods) from the base class.
Here’s a simple example:
In this snippet, the Student class inherits from the Person class. It reuses the name and age attributes and methods from the Person class and adds a new attribute major and a new display method to show the student's major.
When you declare a derived class, you specify the base class it inherits from. This is done using the : public BaseClass syntax. The derived class can then extend or override the functionality of the base class.
In our example:
- The
Personclass is the base class. - The
Studentclass is the derived class, inheritingnameandagefrom thePersonclass. - The
Studentclass also adds a new member,major, and overrides thedisplaymethod to include information about the major.- Notice how
Student::display()callsPerson::display()to reuse the base class functionality before adding its own details. - The
greetmethod is also called from thedisplaymethod to show how the derived class can access base class methods using thethispointer.
- Notice how
Notice how Student::display() calls Person::display() to reuse the base class functionality before adding its own details.
