To declare inheritance in C++, we add : access-modifier BaseClassName after the derived class name. To say that Student inherits from `Person, we would write:
class Person {
// base class members
};
class Student : public Person {
// derived class members
};
In this example, Student is the derived class and Person is the base class. The public keyword indicates that the inheritance is public. This means that all the public members of the base class are accessible in the derived class. To see what this means, consider the example below. (All of the members are public to simplify this first demonstration. We will fix that soon.)
Because it inherits from Person, Student has access to all of the public members of Person. That is why the Student::study function can access the m_name variable on line 20.
In main, we set the m_major which belongs to Student directly, but we also set the m_name, m_age variables that are inherited from Person. (lines 20 and 26-27)
The best way to picture this relationship is to imagine that every Student object has a Person object inside it. If we access s.m_age or s.m_major, we are actually accessing the m_age and m_major members of the Person object inside s:
What we have diagramed is very similar to what happens at a low level in memory. There is memory reserved for the Person object inside the chunk of memory used for the Student. (Codelens will not show this, but a debugger in an IDE should indicate that m_name and m_age are in a nested object.).
This low-level nested structure is not that different than how composition stores nested objects. However, the way we access the data in that nested object is different. In composition, the nested object has a name, and we access it using that name. In inheritance, the nested object does not have its own name. Instead, we access its members as if they were members of the derived class.
When making a UML diagram, we only list the members that are defined directly in each class. So even though a Student has m_name, m_age, and introduce() that are available via inheritance, they are not shown in the Student class.
We will only consider public inheritance in this book (: public BaseClassName). However, there are also non-public forms of inheritance (protected and private). These forms restrict access to the base class members. For example, if a class inherits from another class using private inheritance, all the public members of the base class become private members of the derived class.
If you forget to write public while declaring inheritance and just write : BaseClassName, the inheritance will default to private and not behave as described here.