Inheritance (C++)

Inheritance lets one class (the derived class) reuse and extend the members of another class (the base class). It models 'is-a' relationships and avoids duplicating code.

C++

You write inheritance with a colon and an access specifier, as in `class Cat : public Animal`. The derived class inherits the base's members and can add new ones or override existing behavior.

Public inheritance is the most common form. Combined with virtual functions, inheritance enables polymorphism, where a base-class pointer can call the right derived-class behavior at runtime.

Syntax

class Derived : public Base { /* members */ };

Examples

C++

#include <iostream>

class Animal {
public:
    void breathe() { std::cout << "breathing" << std::endl; }
};

class Cat : public Animal {
public:
    void meow() { std::cout << "meow" << std::endl; }
};

int main() {
    Cat c;
    c.breathe();
    c.meow();
    return 0;
}

Output:

breathing
meow

Learn it in a lesson

See also

Back to the Dictionary