Chapter 3 – Object-Oriented Programming: Part 2

Inheritance

Inheritance is one of the core concepts of object-oriented programming (OOP) languages. It is a mechanism where you can derive a class from another class for a hierarchy of classes that share a set of attributes and methods.

public inheritance

This is called a “is-a” relationship => a Car is a Vehicle, a Bus is a Vehicle.

With inheritance, we can make sure that we write code in only one place, and we inherit in derived classes.

Here, both FirstClass and SecondClass have a data variable of type int in their class, and can call the execute function.

private inheritance

This is called private inheritance – is also the default access modifier when inheriting classes (see 2nd line, where we skip the private keyword).

This is a “has-a” relationship – a Car has an Engine.

Composition over inheritance

Assuming we have the following base class:

We can either inherit privately from it, and use the method directly =>

Or we can use composition, and use the method through the object itself.

Ideally, we should always prefer composition over inheritance.

To the caller of the car, nothing changes.

Construction / Destruction order

What will be displayed when creating a Derived object? What about when it is destroyed?

When we create a Derived object, the constructor of the base class is called first – the construction starts from the base to the top (Base Derived).

When we destroy a Derived object, the destructor of the derived class is called first – the destruction starts from the top to the base (~Derived ~Base)

You may also like...