example3_multiple_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
46
47
#include <iostream>
#include <string>

class Flyable {
public:
    virtual void fly() const {
        std::cout << "Flying..." << std::endl;
    }
};

class Swimmable {
public:
    virtual void swim() const {
        std::cout << "Swimming..." << std::endl;
    }
};

class Duck : public Flyable, public Swimmable {
private:
    std::string name;

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

    void introduce() const {
        std::cout << "I'm " << name << " the duck." << std::endl;
    }

    // Optionally override inherited methods
    void fly() const override {
        std::cout << name << " is flying." << std::endl;
    }

    void swim() const override {
        std::cout << name << " is swimming." << std::endl;
    }
};

int main() {
    Duck duck("Donald");

    duck.introduce();
    duck.fly();
    duck.swim();

    return 0;
}
Back to subclass