Inheritance

Code reuse through inheritance

Interview Relevant: Core OOP pillar

Inheritance

Derive new classes from existing ones.

Code Examples

Basic inheritance and access control.

cpp
1// Base class
2class Animal {
3protected:
4    string name;
5
6public:
7    Animal(string n) : name(n) {}
8
9    void eat() {
10        cout << name << " is eating" << endl;
11    }
12};
13
14// Derived class
15class Dog : public Animal {
16public:
17    Dog(string n) : Animal(n) {}  // Call base constructor
18
19    void bark() {
20        cout << name << " says Woof!" << endl;
21    }
22};
23
24Dog d("Buddy");
25d.eat();   // Inherited
26d.bark();  // Own method
27
28// Inheritance access specifiers
29class A : public B {};     // public stays public
30class A : protected B {};  // public becomes protected
31class A : private B {};    // Everything becomes private
32
33// Using base class methods
34class Cat : public Animal {
35public:
36    Cat(string n) : Animal(n) {}
37
38    void eat() {  // Override
39        cout << name << " eats gracefully" << endl;
40        Animal::eat();  // Call base version
41    }
42};

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In