example1_basic_inheritance.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <string>

class Animal {
protected:
    std::string name;

public:
    Animal(const std::string& n) : name(n) {}

    void eat() const {
        std::cout << name << " is eating." << std::endl;
    }

    void makeSound() const {
        std::cout << name << " makes a sound." << std::endl;
    }
};

class Dog : public Animal {
public:
    Dog(const std::string& n) : Animal(n) {}

    void wagTail() const {
        std::cout << name << " is wagging its tail." << std::endl;
    }

    void makeSound() const {
        std::cout << name << " barks: Woof!" << std::endl;
    }
};

int main() {
    Animal animal("Generic Animal");
    Dog dog("Buddy");

    animal.eat();
    animal.makeSound();

    dog.eat();  // Inherited from Animal
    dog.makeSound();  // Overridden method
    dog.wagTail();  // Dog-specific method

    return 0;
}
Back to subclass