Inheritance in C++

What is Inheritance?

a. Provides a way to create a new class from an existing class
b. The new class is a specialized version of the existing class
c. Inheritance establishes an “is a” relationship between classes.

i. A poodle is a dog
ii. A car is a vehicle
iii. A flower is a plant

d. Terminology:

i. Base class (or parent) – inherited from
ii. Derived class (or child) – inherits from the base class
iii. Notation: class Student // base class { . . . }; class UnderGrad : public student // derived class { . . . };
f. An object of a derived class ‘is a(n)’ object of the base class

g. Example:

i. an UnderGrad is a Student
ii. a Mammal is an Animal

h. A derived object has all of the characteristics of the base class

i. An object of the derived class has:
i. all members defined in child class
ii. all members declared in parent class

j. An object of the derived class can use:

i. all public members defined in child class
ii. all public members defined in parent class

k. Use inheritance for these properties (to save time/reduce work)

Protected Members and Class Access

a. protected member access specification: like private, but accessible by:
i. Member functions of the class that originally declared the member.
ii. Friends of the class that originally declared the member.
iii. Classes derived with public or protected access from the class that originally declared the member.
iv. Direct privately derived classes that also have private access to protected members.

b. Class access specification: determines how private, protected, and public members of base class are inherited by the derived class
c. Access Modifiers
i. public – object of derived class can be treated as object of base class (not vice-versa)
ii. protected – more restrictive than public, but allows derived classes to know details of parents
iii. private – prevents objects of derived class from being treated as objects of base class.

Class diagram for inheritance:

Consider the GradedActivity, FinalExam, PassFailActivity, PassFailExam hierarchy

inheritance-class-diagram

 

 

Leave a Reply