A derived class inherits the members of its base class and can add or customise behaviour. Public inheritance models an is-a relationship.
Basics
#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
}Animal()
Dog()
Rex eats
Rex the beagle barks
~Dog()
~Animal()Inheritance access
| Base member is… | public inheritance | protected inheritance | private inheritance |
|---|---|---|---|
public | public | protected | private |
protected | protected | protected | private |
private | inaccessible | inaccessible | inaccessible |
publicinheritance = is-a (aDogcan be used wherever anAnimal&is expected). 99% of the time this is what you want.privateinheritance = implemented-in-terms-of — usually better expressed with composition (a member).class D : Bdefaults to private inheritance;struct D : Bto public.
Hiding, using and calling the base version
#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);
}Derived::greet, then Base::greet
Base::greet(3)Composition vs inheritance
What is not inherited from a base class?