0% found this document useful (0 votes)
9 views

Lect03 CPP Inheritance

The document discusses inheritance and aggregation in object-oriented programming. It defines inheritance as allowing a new class to inherit attributes and functions from an existing class. It describes different types of inheritance like public, private, and protected inheritance and how they affect access levels. It also discusses hierarchical organization of concepts and aggregation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Lect03 CPP Inheritance

The document discusses inheritance and aggregation in object-oriented programming. It defines inheritance as allowing a new class to inherit attributes and functions from an existing class. It describes different types of inheritance like public, private, and protected inheritance and how they affect access levels. It also discusses hierarchical organization of concepts and aggregation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

INHERITANCE & AGGREGATION

Bùi Tiến Lên

2022
Contents

1. Introduction to inheritance

2. Hierarchical organization of concepts

3. Types of inheritance

4. Derived class

5. Multiple inheritance

6. Aggregation

7. Workshop
Introduction to inheritance
What Is Inheritance?
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of Concept 1
inheritance

Derived class Inheritance allows a new class to be based on an existing class. The new class
Multiple inherits all the member variables and functions (except the constructors and
inheritance
destructor) of the class it is based on.
Aggregation

Workshop

4
Inheritance and the “Is a” Relationship
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of When one object is a specialized version of another object, there is an “is a”
inheritance
relationship between them. For example, a grasshopper is an insect. Here are a
Derived class
few other examples of the “is a” relationship.
Multiple
inheritance • A poodle is a dog.
Aggregation
• A car is a vehicle.
Workshop
• A tree is a plant.
• A rectangle is a shape.
• A football player is an athlete.
Inheritance involves a base class and a derived class.
• The base class is the general class and the derived class is the specialized
class.
• The derived class is based on, or derived from, the base class.

5
C++ Syntax of Derivation
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of
inheritance
Syntax
Derived class
class <Derived Class> : <Type Of Inheritance> <Base class>
Multiple
inheritance {
Aggregation public:
Workshop <public attributes/functions>
private:
<private attributes/functions>
};

6
Inheritance in UML
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of • Inheritance between classes.


inheritance

Derived class Base

Multiple
inheritance

Aggregation

Workshop
Derived1 Derived2

7
Examples of Inheritance Taken from Daily Life
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of
inheritance
Base Class Example Derived Classes
Derived class Fish Goldfish, Carp, Tuna
Multiple Mammal Human, Elephant, Lion, Platypus
inheritance
Bird Crow, Parrot, Ostrich, Kiwi, Platypus
Aggregation
Shape Circle, Polygon
Workshop
Polygon Triangle, Octagon

8
Listing 1
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of #include <iostream >


inheritance
using namespace std;
Derived class class Fish {
Multiple public:
inheritance bool FreshWaterFish;
Aggregation
void Swim () {
if (FreshWaterFish)
Workshop
cout << "Swims in lake" << endl;
else
cout << "Swims in sea" << endl;
}
};
class Tuna: public Fish {
public:
Tuna () {
FreshWaterFish = false;
}
};
class Carp: public Fish {

9
Listing 1 (cont.)
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of public:
inheritance Carp () {
Derived class FreshWaterFish = true;
}
Multiple
inheritance
};
int main () {
Aggregation Carp myLunch;
Workshop Tuna myDinner;
cout << "Getting my food to swim" << endl;
cout << "Lunch: ";
myLunch.Swim ();
cout << "Dinner: ";
myDinner.Swim ();
return 0;
}

10
Hierarchical organization of concepts
Class Hierarchies
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of
inheritance
Concept 2
Derived class A base class can also be derived from another class.
Multiple
inheritance • Sometimes it is desirable to establish a hierarchy of classes in which one class
Aggregation inherits from a second class, which in turn inherits from a third class
Workshop
• In some cases, the inheritance of classes goes on for many layers.
ClassA

ClassB

ClassC

12
Hierarchical organization of concepts
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of
• A group of concepts is divided into sub-groups according to some criterion.
inheritance
• We should use only one criterion at a time to classify a group of concepts.
Derived class

Multiple
inheritance Steam giant Catapult

Aggregation

Workshop
Cannon Ram
Gyrocopter

Spearman Swordman Archer Cook


Balloon

Barbarian-axe swinger Phalanx Musketeer Slinger Doctor

13
Hierarchical organization of concepts (cont.)
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of
• Concepts are recursively classified into subgroups
inheritance

Derived class

Multiple
inheritance

Aggregation

Workshop

14
Hierarchical organization of concepts (cont.)
Introduction to
inheritance

Hierarchical
organization of
concepts
Unit
Types of
inheritance

Derived class

Multiple
GroundUnit AirUnit
inheritance

Aggregation

Workshop
MachineUnit OrganicUnit Gyrocopter Balloon

SteamGiant Catapult Cannon Ram MeleeUnit LongRangedUnit SupportUnit

Spearman Swordman BarbarianAxeSwinger Phalanx Archer Musketeer Slinger Cook Doctor

• It is possible to have different ways to create logical hierarchical organization 15


Types of inheritance
Protected Members and Class Access
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of
inheritance
Concept 3
Derived class Protected members of a base class are like private members, but they may be
Multiple accessed by derived classes. The base class access specification determines how
inheritance

Aggregation
private, public, and protected base class members are accessed when they are
Workshop
inherited by the derived classes.

17
Types of inheritance (in C++)
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of • There are 3 types of inheritance in C++:


inheritance

Derived class
• public inheritance: public and protected of the base class become
Multiple public and protected of the derived class.
inheritance • protected inheritance: public and protected of the base class become
Aggregation
protected of the derived class.
Workshop
• private inheritance: public and protected of the base class become
private of the derived class.
• Notes: from now on, if there is no mention of what type of inheritance, it
means public inheritance

18
Types of inheritance (in C++) (cont.)
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of
inheritance Base public Derived Base protected Derived

Derived class
Private Private Private Private
Multiple attributes/methods attributes/methods attributes/methods attributes/methods
inheritance
Protected Protected Protected Protected
Aggregation attributes/methods attributes/methods attributes/methods attributes/methods
Workshop Public Public Public Public
attributes/methods attributes/methods attributes/methods attributes/methods

Base private Derived

Private Private
attributes/methods attributes/methods

Protected Protected
attributes/methods attributes/methods

Public Public
attributes/methods attributes/methods

19
Derived class
Member functions inheritance
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of • Member functions of the base class are inherited in the derived class, except:
inheritance

Derived class
• Constructors
Multiple
• Destructors
inheritance • Assignment operators
Aggregation

Workshop

21
Order of Construction/Deconstruction
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of
inheritance
Concept 4
Derived class The base class’s constructor is called before the derived class’s constructor. The
Multiple destructors are called in reverse order, with the derived class’s destructor being
inheritance
called first.
Aggregation

Workshop When a new object of a derived class is created:


• The constructor of the base class is invoked first.
• Then, the constructor of the derived class is invoked.
• In the constructor of the derived class, we can specify which constructor of
the base class is called. Otherwise, the default constructor of the base class
will be invoked.
When an object of the derived class finishes its lifespan:
• The destructor of the derived class is invoked first.
• Then, the destructor of the base class is called later.
22
Order of Construction/Deconstruction (cont.)
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of Destructors
inheritance

Derived class

Multiple
inheritance

Aggregation

Workshop

Constructors

23
Base Class Initialization
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of • Using initialization lists and in invoking the appropriate base class
constructor via the constructor of the derived class
inheritance

Derived class

Multiple class Base {


inheritance
public :
Aggregation
Base(int SomeNumber ) { // overloaded constructor
Workshop
// Do something with SomeNumber
}
};
class Derived : public Base {
public :
Derived (): Base (25) { // instantiate class Base with
// argument 25
// derived class constructor code
}
};

24
Derived Class Overriding Base Class’ Methods
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of • Sometimes, we need to “re-define” the member functions of a base class in a


inheritance

Derived class
derived class. It can be done by implements the same functions in the class
Multiple
Derived with the same return values and signatures as in the class Base it
inheritance inherits from
Aggregation

Workshop Notes
This re-definition will hide other overloading member functions of this
function from the base class.

25
Listing 2
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of # include <iostream >


inheritance
using namespace std;
Derived class
class Fish {
Multiple private :
inheritance
bool FreshWaterFish ;
Aggregation
public :
Workshop
// Fish constructor
Fish(bool IsFreshWater ) : FreshWaterFish ( IsFreshWater ){}
void Swim () {
if ( FreshWaterFish )
cout << " Swims in lake" << endl;
else
cout << " Swims in sea" << endl;
}
};
class Tuna: public Fish {

26
Listing 2 (cont.)
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of public :
inheritance Tuna (): Fish( false ) {}
Derived class void Swim () {
Multiple cout << "Tuna swims real fast" << endl;
inheritance }
Aggregation };
Workshop class Carp: public Fish {
public :
Carp (): Fish(true) {}
void Swim () {
cout << "Carp swims real slow" << endl;
}
};
int main () {
Carp myLunch ;
Tuna myDinner ;
cout << " Getting my food to swim" << endl;

27
Listing 2 (cont.)
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of cout << " Lunch : ";


inheritance myLunch .Swim ();
Derived class cout << " Dinner : ";
Multiple myDinner .Swim ();
inheritance return 0;
Aggregation }
Workshop

28
Invoking Overridden Methods of a Base Class
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of
• If we want to be invoke Fish::Swim(), we need to use the scope resolution
inheritance
operator (::)
Derived class
int main () {
Multiple
inheritance ...
myDinner.Fish :: Swim ();
Aggregation
...
Workshop }

• If our specialized implementations in Tuna:Swim() and Carp::Swim() need


to reuse the base class’ generic implementation of Fish::Swim(), we use the
scope resolution operator (::)
class Carp: public Fish {
public:
Carp (): Fish(true) {}
void Swim () {
cout << "Carp swims real slow" << endl;
Fish :: Swim (); // use scope resolution operator ::
}
}; 29
Problem with re-definition
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of
inheritance class Base { int main () {
Derived class public: Derived obj;
void test () {...} int x, y;
Multiple
inheritance void test(int) {...} ...
void test(int , int) {...} obj.test(x); // OK
Aggregation
}; obj.test(x, y); // compile error
Workshop class Derived : public Base { }
public:
void test(int) {...}
};

• Solution 1: Use the scope resolution operator ::


• Solution 2: Use the using keyword in class Derived to unhide other
overloaded methods
• Solution 3: Override all overloaded methods

30
The Problem of Slicing
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of • What happens when a programmer does the following?


inheritance
Derived objectDerived;
Derived class
Base objectBase = objectDerived;
Multiple
inheritance
• Or, alternatively, what if a programmer does this?
Aggregation

Workshop void FuncUseBase(Base input);


...
Derived objectDerived;
FuncUseBase(objectDerived);

• The compiler copies only the Base part of objectDerived—that is, not the
complete object—rather than only that part of it that would fit Base.
Concept 5
The unwanted reduction of the part of data that makes the Derived a
specialization of Base is called slicing.
31
The Problem of Slicing (cont.)
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of
inheritance
Human Director
Derived class

Multiple
inheritance

Aggregation

Workshop

assignment

Caution
To avoid slicing problems, don’t pass parameters by value.
32
Assignment operator
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of
• Assignment operator is not inherited from the base class. To implement the
inheritance
assignment operator for the derived class:
Derived class
• First, calling the assignment operator of the base class to assign data
Multiple
inheritance members of the base class .
Aggregation • Then, implement the assignment for data member of the derived class
Workshop part.
Derived & operator = ( const Derived & CopySource )
{
if(this != & copySource ) { // do not copy itself
// the base class copy
Base :: operator =( CopySource )
// the derived class copy
}
return *this;
}
33
Multiple inheritance
Multiple inheritance
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of
inheritance
Concept 6
Derived class Multiple inheritance is when a derived class has two or more base classes.
Multiple
inheritance

Aggregation

Workshop

35
Listing 3
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of #include <iostream >


inheritance
using namespace std;
Derived class class Mammal {
Multiple public:
inheritance void FeedBabyMilk () {
Aggregation
cout << "Mammal: Baby says glug!" << endl;
}
Workshop
};
class Reptile {
public:
void SpitVenom () {
cout << "Reptile: Shoo enemy! Spits venom!" << endl;
}
};
class Bird {
public:
void LayEggs () {
cout << "Bird: Laid my eggs , am lighter now!" << endl;
}

36
Listing 3 (cont.)
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of };
inheritance class Platypus: public Mammal , public Bird , public Reptile {
Derived class public:
void Swim () {
Multiple
inheritance
cout << "Platypus: Voila , I can swim!" << endl;
}
Aggregation };
Workshop int main () {
Platypus realFreak;
realFreak.LayEggs ();
realFreak.FeedBabyMilk ();
realFreak.SpitVenom ();
realFreak.Swim ();
return 0;
}

37
Aggregation
Aggregation
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of
inheritance
Concept 7
Derived class Aggregation occurs when a class contains an instance of another class.
Multiple
inheritance
• When an instance of one class is a member of another class, it is said that
Aggregation

Workshop
there is a “has a” relationship between the classes.
• For example, the relationships that exist among the Course, Instructor,
and TextBook classes can be described as follows:
• The course has an instructor.
• The course has a textbook.

39
Aggregation
Introduction to
inheritance

Hierarchical
organization of
concepts
Course
Types of
courseName : string
inheritance
instructor : Instructor&
Derived class textBook : TextBook&

Multiple Course(name : string, instr : &Instructor, text : TextBook&) :


inheritance print() : void

Aggregation

Workshop

Instructor TextBook

lastName : string title : string


firstName : string author : string
officeNumber : string publisher : string

Instructor(lname : string, fname : string, office : string) : TextBook(textTitle : string, auth : string, pub : string) :
Instructor(obj : Instructor&) : TextBook(obj : TextBook&) :
set(lname : string, fname : string, office : string) : void set(textTitle : string, auth : string, pub : string) : void
print() : void print() : void

40
Examples of Aggregation Taken from Daily Life
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of
inheritance
Part Whole
Derived class Motor Car (Car has a Motor)
Multiple Heart Mammal (Mammal has a Heart)
inheritance
Refill Pen (Pen has a Refill)
Aggregation
Moon Sky (Sky has a Moon)
Workshop

41
Workshop
Quiz
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of 1. I want some base class members to be accessible to the derived class but not
inheritance

Derived class
outside the class hierarchy. What access specifier do I use?
Multiple
.........................................................................
inheritance .........................................................................
Aggregation
.........................................................................
Workshop
2. If I pass an object of the derived class as an argument to a function that
takes a parameter of the base class by value, what happens?
.........................................................................
.........................................................................
.........................................................................

43
Quiz (cont.)
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of 3. Which one should I favor? Private inheritance or composition?


inheritance
.........................................................................
Derived class
.........................................................................
Multiple
inheritance .........................................................................
Aggregation
4. How does the using keyword help me in an inheritance hierarchy?
Workshop
.........................................................................
.........................................................................
.........................................................................
5. A class Derived inherits private from class Base. Another class
SubDerived inherits public from class Derived. Can SubDerived access
public members of class Base?
.........................................................................
.........................................................................
.........................................................................
44
Exercises
Introduction to
inheritance

Hierarchical
organization of
concepts

Types of • Programming Challenges of chapter 13 [Gaddis, 2014]


inheritance

Derived class
1. Employee and ProductionWorker Classes
Multiple
2. ShiftSupervisor Class
inheritance 3. TeamLeader Class
Aggregation

Workshop

45
References

Deitel, P. (2016).
C++: How to program.
Pearson.
Gaddis, T. (2014).
Starting Out with C++ from Control Structures to Objects.
Addison-Wesley Professional, 8th edition.
Jones, B. (2014).
Sams teach yourself C++ in one hour a day.
Sams.

You might also like