Introduction to Inheritance
Objectives
We would like to :
Explore the basics of inheritance in c++
Notes
This is from the book, but also from Gregorie and others.
This is just an introduction, light on restrictions and such.
We will be back and formalize things more later.
In the real world, we frequently look for "relationships" between things.
Two in object oriented design are is-a and has-a
A student is a person.
A student has a grade point average
Let's examine the student person relationship a bit
For simplicity, a person has a name and a role.
On top of that a student has a GPA.
If we were writing a program in our current style, we could
Implement a person class and a student class separately
Implement a student class and make everyone a student
The problem with the first is that they will have the same code, but it will not be shared.
The problem with he second is that people will have extra properties (GPA)
Inheritance allows us to solve this problem.
A person has properties that ALL people will have, therefore they will form a
base class
.
A student has all of the properties of a person, with some added, so they will form a
derived class
.
The student will inherit all of the properties of the person.
The student can override some of the properties if they wish, replacing them with their own implementation.
To do this
Build a base class that contains all the data/methods of ALL things
Build (a/some) derived class(es) that modify and add specific things to those classes.
This can be done further (ie graduate student derived from student, undergrad student derived from student)
Syntax:
class derivedClassIdentifier: [public/private/protected] baseClassIdentifier{ // class members }
The derived class has access to all public methods/data of the parent/base class.
This depends partially on the public/private/protected choice in the class line
And we will explore this more in the future.
The derived class does not have access to the private methods/data of the parent/base class.
The derived class, however, contains all of the data of the parent/base class.
Several new things
The keyword
virtual
says that we expect this function to be replaced in derived classes.
The keyword
override
is optional, but says that this function is overriding some function in a parent/base class.
Take a look at PersonT.[h,cpp] and people.cpp in the code directory.