Inheritance

Inheritance is a method of code reuse. It works by having a class extend another.

The class that is extended is called the base or parent class and the class that does the extending is called the derived or child class. The syntax is simple:

class Parent {};

class Child : public Parent {};

The child class will have all the attributes of the parent class and can be customized further. You can access public attribute but not private ones. For that, we have to go through getters or setters. Friendship is not inherited.

We can access members of the parent class by declaring them public (bad) or by using the third access modifier, protected. Protected access gives access to the current class and all sub-classes.

class Point {
    // Methods and constructors here
protected:
    int m_x;
    int m_y;
};

What we’ve talked about so far is public inheritance. There is also protected and private inheritance. The difference is what happens to the access modifiers from the parent class. In public inheritance, they stay the same, with protected inheritance, public attributes become protected, and with private inheritance, both public and protected attributes become private. Public inheritance is the most commonly used.

When calling constructors, the parent constructor executes first, then the derived one. If there are no constructors specified, the default ones will be used.

Using custom constructors is just as easy. Consider the following code:

class Point {
private:
     int x {};
     int y {};

public:
     Point(int x, int y) : x{x}, y{y} {}
};

class ThreeDPoint: public Point {
private:
     int z {};

public:
    ThreeDPoint(int x, int y, int z) : Point{x, y}, z{z} {}
};

The ThreeDPoint class simply calls the parent constructor in the initializer list. We can’t call the parent constructor in the body of the derived constructor as this would simply create a local instance of the parent.

Copy constructors work in a similar way. Consider the following code:
class Point {
private:
    int x {};
    int y {};
public:
    Point(const Point &source);
};


class ThreeDPoint: public Point {
private:
    int z {};
public:
    ThreeDPoint(const ThreeDPoint &source) : Point{source}, z{source.z} {}
};

The copy constructor simply calls the base constructor with the source. The compiler slices the object down to the base class. If we don’t create a copy constructor, the compiler will create one for us that does member-wise copies.

Destructors are called in the reverse order to constructors, so derived to base.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.