Inheritance in C++
Inheritance (class Dog : public Animal) builds a new class from an existing one, inheriting its members and adding or specializing behavior — the is-a relationship: every Dog is an Animal. Public inheritance models substitutability (a Dog works wherever an Animal is expected); private/protected inheritance model implementation reuse instead.
Base parts construct before derived parts (and destruct in reverse), and constructors are not inherited by default (though using Base::Base; can pull them in since C++11). Inheritance's real power unlocks with virtual functions — without them you get reuse but no polymorphism.
is-a modeling
class Dog : public Animal says every Dog object contains a full Animal subobject plus Dog's own additions.
Access carries over
Public inheritance keeps public members public in the child; private base members stay inaccessible even to the child.
Construction order
Base constructor runs first, then the derived one; destruction reverses. The base is always fully formed before derived code touches it.
Reuse vs polymorphism
Plain inheritance reuses code; runtime polymorphism needs virtual functions on top — inheritance alone dispatches statically.
#include <iostream>#include <string> class Animal {public: std::string name; explicit Animal(const std::string& n) : name(n) {}}; class Dog : public Animal {public: explicit Dog(const std::string& n) : Animal(n) {}}; int main() { Dog d("Rex"); std::cout << d.name << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.