Learn C++
#include "oopbasics/inheritance.hpp"

Inheritance in C++

//concept

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.

//how it works
1

is-a modeling

class Dog : public Animal says every Dog object contains a full Animal subobject plus Dog's own additions.

2

Access carries over

Public inheritance keeps public members public in the child; private base members stay inaccessible even to the child.

3

Construction order

Base constructor runs first, then the derived one; destruction reverses. The base is always fully formed before derived code touches it.

4

Reuse vs polymorphism

Plain inheritance reuses code; runtime polymorphism needs virtual functions on top — inheritance alone dispatches statically.

//example
#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;
}
Output
Rex
1Dog's constructor forwards n to Animal's constructor in its initializer list — the base subobject forms first.
2d inherits the name member, reading it directly even though Dog declares no members of its own.
3Rex prints, showing the derived object fully functioning through inherited state.
//use cases
Specializing general concepts (Shape→Circle, Account→SavingsAccount) without duplicating shared code
Guaranteeing base initialization via initializer-list forwarding
Choosing public inheritance for substitutability, composition or private inheritance otherwise
Layering virtual functions on top when behavior (not just data) must vary

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.