Skip to content
  • Inheritance & Access Specifiers · C++

Inheritance & Access Specifiers

LearnViaNotes @learnvianotes· 2 min read

A derived class inherits the members of its base class and can add or customise behaviour. Public inheritance models an is-a relationship.

Basics

C++
#include <iostream>
#include <string>

class Animal {
public:
    explicit Animal(std::string name) : name_(std::move(name)) { std::cout << "Animal()\n"; }
    ~Animal() { std::cout << "~Animal()\n"; }
    void eat() const { std::cout << name_ << " eats\n"; }
protected:
    std::string name_;                 // visible to derived classes, not to outsiders
};

class Dog : public Animal {
public:
    Dog(std::string name, std::string breed)
        : Animal(std::move(name)), breed_(std::move(breed)) { std::cout << "Dog()\n"; }   // base first
    ~Dog() { std::cout << "~Dog()\n"; }
    void bark() const { std::cout << name_ << " the " << breed_ << " barks\n"; }
private:
    std::string breed_;
};

int main() {
    Dog d("Rex", "beagle");
    d.eat();          // inherited
    d.bark();         // added
}
Output
Animal()
Dog()
Rex eats
Rex the beagle barks
~Dog()
~Animal()

Inheritance access

Base member is…public inheritanceprotected inheritanceprivate inheritance
publicpublicprotectedprivate
protectedprotectedprotectedprivate
privateinaccessibleinaccessibleinaccessible
  • public inheritance = is-a (a Dog can be used wherever an Animal& is expected). 99% of the time this is what you want.

  • private inheritance = implemented-in-terms-of — usually better expressed with composition (a member).

  • class D : B defaults to private inheritance; struct D : B to public.

Hiding, using and calling the base version

C++
#include <iostream>

struct Base {
    void greet() const { std::cout << "Base::greet\n"; }
    void greet(int n) const { std::cout << "Base::greet(" << n << ")\n"; }
};

struct Derived : Base {
    using Base::greet;                 // without this, greet(int) would be hidden
    void greet() const {
        std::cout << "Derived::greet, then ";
        Base::greet();                 // call the base version explicitly
    }
};

struct WithCtors : Base {
    using Base::Base;                  // inherit constructors (C++11)
};

int main() {
    Derived d;
    d.greet();
    d.greet(3);
}
Output
Derived::greet, then Base::greet
Base::greet(3)

Composition vs inheritance

What is not inherited from a base class?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report