example3_inheritance_virtual_functions.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
#include <iostream>

class Animal {
public:
    virtual void speak() const {
        std::cout << "Animal makes a sound." << std::endl;
    }
};

class Dog : public Animal {
public:
    void speak() const override {
        std::cout << "Dog barks." << std::endl;
    }
};

class Cat : public Animal {
public:
    void speak() const override {
        std::cout << "Cat meows." << std::endl;
    }
};

void makeAnimalSpeak(const Animal& animal) {
    animal.speak();  // Calls the appropriate speak() method based on the object type
}

int main() {
    Dog dog;
    Cat cat;

    makeAnimalSpeak(dog);  // Outputs: Dog barks.
    makeAnimalSpeak(cat);  // Outputs: Cat meows.

    return 0;
}
Back to polymorphism