example4_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
#include <iostream>
#include <string>

class Animal {
protected:
    std::string species;
    int age;

public:
    Animal(const std::string& s, int a) : species(s), age(a) {
        std::cout << "Animal constructed" << std::endl;
    }

    virtual void makeSound() const = 0;
};

class Dog : public Animal {
private:
    std::string breed;

public:
    Dog(const std::string& b, int a)
        : Animal("Canis lupus familiaris", a), breed(b) {
        std::cout << "Dog constructed" << std::endl;
    }

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

    void display() const {
        std::cout << breed << " dog, age " << age << std::endl;
    }
};

int main() {
    Dog myDog("Labrador", 5);
    myDog.display();
    myDog.makeSound();

    return 0;
}
Back to initializer_lists