Inheritance

<aside> 💡 Inheritance is a mechanism of reusing and extending existing classes without modifying them, thus producing hierarchical relationships between them.

</aside>

Example

Book is the superclass Text and Comic are children classes

// Base class or super class
class Book {    
    string title;
    string author;
    int length;
    public:
        Book();
        // ...
};

// Derived class or subclasses
class Text : public Book {   
    string topic;
    public:
        Text();
        // ...
};

// Derived class or subclasses
class Comic : public Book {  
    string hero;
    public:
        Comic();
        // ...
};
class Text:public Book {
    // ...
    public: 
        Text(string title, string author, int length, string topic): 
            Book{title, author, length}, // invoke Book ctor in step 2 super class constructed
            topic{topic} // construct topic field in step 3
            {}  // call ctor body in step 4
};

Using the protected access specifier

// Not a good idea to give subclasses unlimited access to fields
// Better Solution - Keep fields private and provide protected accessors/mutators
class Book {
    string title;
    string author;
    int length;
    protected:
        // Subclasses can call these, but no one else
        string getTitle() const;
        void setAuthor(string newAuthor);
    public:
        Book();
        bool isHeavy() const;
};

Object constructions steps

  1. Allocate Space
  2. NEW: The superclass part is constructed
  3. field are constructed
  4. body of constructor runs

(Note: if no copy/move constructor defined for child class, then the parents’ one will be used)