Chapt 11. Inheritance

11.1. Introduction to Inheritance (Learn C++)

‘Inheritance’ is one of two ways to build complex class (the other is ‘composition’)

reusability‘ is fundamental idea of inheritance

base (or parent): the object being inherited from i.e. fruit

derived (or child): the object doing inheriting i.e. apple

by default, children inherit all of properties from parent

children can redefine, hide inherited properties and add new properties

11.2. Basic inheritance in C++ (Learn C++)

derived class inherit all of member variables and functions of base class

inheritance hierarchy: must be from ‘general’ to ‘specific’

11.3. Order of construction of derived class (Learn C++)

execute constructors from base(top) to derived(leaf) following inheritance tree

∗ Order of destruction: from derived(leaf) to base(top)

Source Code

11.4. Constructors and initialization of derived class (Learn C++)

C++ allows to set specific base constructor to call before derived constructor

 Source Code

11.5. Access Specifiers (Learn C++)

A. Member Access Specifiers

1. Public: derived and outside can directly access it

3. Private: derived and outside can’t directly access it

3. Protected: only derived can access it

Source Code

B. Inheritance Access Specifiers

1. Public(mostly used): all members inherited maintain member access specifiers

2. Private(rarely used): all members inherited become private

3. Protected(not used): public members inherited become protected

Note! : It only affect outside access, not in immediate derived class

Source Code

11.6. Add, Redefine, Insert and Hide (Learn C++)

A. Add new functionality

can define new functions in derived

Source Code

B. Redefine inherited functionality : Polymorphism

can override inherited functions in derived what makes ‘polymorphism

 ∗ redefined function does not inherit the access specifier

Source Code

C. Insert inherited functionality

can insert inherited function in another function → reusability

* recommend use scope resolution operator(::) to make explicit

Source Code

D. Hide inherited functionality

can change access specifier of inherited functions directly accessible in derived

* ‘private’ can’t change to public or protected, because it is invisible in derived

Source Code

11. 7. Multiple Inheritance (Learn C++)

Conclusion: It turns out that most of problems can be handled by ‘Single Inheritance’

 Therefore, think once again before using multiple inheritance

 because, it can lead to complex, naming conflict and diamond problem

11. 8. Virtual base classes (Learn C++)

‘virtual’ keyword means base class will be created later and shared on inheritance

therefore, it is responsible for most derived to construct virtual base class

can handle the diamond problem one of issue in multiple inheritance