Chapter 26: Inheritance

Introduction

Inheritance is a fundamental concept in object-oriented programming that allows a class (derived class) to inherit properties and behaviors (members and functions) from another class (base class).

Basic Syntax

class BaseballPlayer : public Person

Protected members can be accessed by members, friends, and derived classes.

Inheritance Types

The default inheritance type is private.

Access specifier in base class Access specifier when inherited publicly Access specifier when inherited privately Access specifier when inherited protectedly
Public Public Private Protected
Protected Protected Private Protected
Private Inaccessible Inaccessible Inaccessible

Example

class Derived: public Base
{
public:
    int getValue() const = delete; // mark this function as inaccessible
    using Base::print;
    // make all Base::print() functions eligible for overload resolution
    // you can't change from private because Derived class has no access to private Base members
};

Accessing Base Class Functions

Derived derived;

// We can call the Base::getValue() function directly
std::cout << derived.Base::getValue();

// Or we can upcast Derived to a Base reference and getValue() will resolve to Base::getValue()
std::cout << static_cast<Base&>(derived).getValue();

Multiple Inheritance

Multiple inheritance allows a class to inherit from more than one base class.

Example

class Teacher : public Person, public Employee

// Specify which function to use in case of ambiguity
c54G.USBDevice::getID();

Avoid multiple inheritance unless alternatives lead to more complexity.

Constructor Initialization in Derived Classes

When a derived class is instantiated, the base class constructor is called first.

Example

class Derived : public Base
{
public:
    Derived()
        : Base(params...) // call base constructor
    {
        // derived class constructor body
    }
};

Conclusion

Inheritance allows for code reuse and the creation of a hierarchical class structure. Understanding how to use different types of inheritance and manage access to base class members is crucial for designing robust and maintainable object-oriented systems.