Sobes.tech
Junior — Middle

Can you explain the concept of polymorphism in object-oriented programming?

sobes.tech AI

Answer from AI

Polymorphism in object-oriented programming is the ability of objects of different classes to respond to the same messages (method calls) in different ways. This allows using a single interface to work with different types of objects.

For example, in C++, you can define a base class with a virtual function, and override it in derived classes:

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

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

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

void makeAnimalSpeak(Animal* animal) {
    animal->speak(); // the method call depends on the actual type of the object
}

Thus, the same call to speak() behaves differently depending on the object type, which is polymorphism.