Create a base class `Animal` with function `speak()`. Derive classes `Dog` and `Cat`, override `speak()` function to display "Bark" and "Meow" respectively.

SOLUTION....

C++ Virtual Function Example

#include <iostream>
using namespace std;

// Base class
class Animal {
public:
    virtual void speak() {   // Virtual function
        cout << "Animal sound" << endl;
    }
};

// Derived class: Dog
class Dog : public Animal {
public:
    void speak() override {  // Override function
        cout << "Bark" << endl;
    }
};

// Derived class: Cat
class Cat : public Animal {
public:
    void speak() override {  // Override function
        cout << "Meow" << endl;
    }
};

// Main function
int main() {
    Animal* a;   // Base class pointer

    Dog d;
    Cat c;

    // Pointing to Dog object
    a = &d;
    a->speak();   // Calls Dog's speak()

    // Pointing to Cat object
    a = &c;
    a->speak();   // Calls Cat's speak()

    return 0;
}
    

OUTPUT

Leave a Reply

Your email address will not be published. Required fields are marked *