Chapter 18 C Inheritance and Polymorphism n n






















- Slides: 22
Chapter 18 C++ Inheritance and Polymorphism n n n By C. Shing ITEC Dept Radford University
Objectives n n n Understand how to create abstract class Understand how to use inheritance Understand how to use polyporphism 2
Inheritance n Inheritance tree n n n Parent: super-class (base class), larger set of objects, general functions Child: sub-class (derived class), subset of parent objects, special functions Parent class-child class relationship: child object “is a” parent object 3
Types of Inheritance 3 types of inheritance: n 1. 2. Public: derived class is public, most popular, used here every non-member class can access derived public functions Protected: derived classes are protected classes Only member function can access those functions Private: derived classes are private classes Only member function can access those functions 4
Public Inheritance Implementation Inheritance implementation Form: class child_class: public parent_class { Public: … Private: … } n 5
Inheritance Example Geometry Point 6
Inheritance Example (Cont. ) Point Circle Line Triangle Rectangle 7
Inheritance Example (Cont. ) Triangle Tetrahedran 8
Inheritance Example (Cont. ) Rectangle Parallelgram 9
Abstract Class n n The class includes only all specification No implementation 10
Abstract Class (Cont. ) n Example: Geometry class geometry. h 11
Inherited Class n Example: Point class point. h point. cpp 12
Inherited Class (Cont. ) n Example: Line class line. h line. cpp 13
Inherited Class (Cont. ) n Example: Triangle class triangle. h triangle. cpp 14
Inherited Class (Cont. ) n Example: Tetrahedran class tetrahedran. h tetrahedran. cpp 15
Inherited Class (Cont. ) n Example: Rectangle class rectangle. h rectangle. cpp 16
Inherited Class (Cont. ) n Example: Parallelgram class parallelgram. h parallelgram. cpp 17
Inherited Class (Cont. ) n Example: Circle class circle. h circle. cpp 18
Polymorphism n Decide data type of the class during run-time in inheritance tree. 19
Polymorphism (Cont. ) n Example: polymorphism. cpp 20
Polymorphism (Cont. ) n Example: whole program polymorphism_whole. cpp 21
References Deitel & Deitel: C How to Program, 4 th ed. , Chapter 19 & 20, Prentice Hall n 22