Mastering C++
Mastering Inheritance and Polymorphism
Classes In C++Inheritance lets one class use all the public and protected members of another class, creating an "is-a" relationship. Think of it like a parent-child relationship, where the child class "inherits" the attributes and behaviors of the parent class.
This is helpful for organizing your code when you have multiple related data types that share common features.
Here are some simple real-life examples of inheritance, with the Person class as the parent:
An Employee is a Person, a Student is a Person, a Teacher is a Person, a Doctor is a Person, and an Athlete is a Person.
Inheritance - A
When a child class inherits from a parent class, it can access the public and protected members of the parent class but cannot directly access private members.
Protected members are like private members, but with one key difference: child classes can access them directly. This makes protected members useful when you want to share data or functionality with child classes while keeping it hidden from outside code.
Let’s create a parent class, Person, with the attributes name, age, and a private sin (Social Insurance Number). Then, we’ll create an Employee class that inherits from Person and adds jobTitle and salary.
Person Class:
class Person {
protected:
string name;
int age;
private:
string sin; // Private member (not accessible to child classes)
public:
Person(string n, int a, string ssn) : name(n), age(a), sin(ssn) {}
};Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 21 more lessons in Mastering C++.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel any time.