C++ Polymorphism

Polymorphism, which is defined as having "many forms," happens when there are several classes that are connected to one another by inheritance.

Reusing properties and methods from an existing class while creating a new class is helpful for code reuse.

Consider an example, an Animal base class with the function animalSound (). Derived classes of animals include cats, dogs, and birds, each of which has its unique animal sound (the dog barks, and the cat meows, etc.)

Code:



    #include "iostream"
    #include "string"
    using namespace std;

    // Base class
    class Animal {

      public:
        void animalSound() {
        cout << "The animal�s sound \n";
    }
    };

    // Derived class
    class Cat : public Animal {
      public:
        void animalSound() {
        cout << "The cat says: meow \n";
    }
    };

    // Derived class
    class Dog : public Animal {
      public:
        void animalSound() {
        cout << "The dog says: bow wow \n";
    }
    };

    int main() {

      Animal myAnimal;
      Cat myCat;
      Dog myDog;
      myAnimal.animalSound();
      myCat.animalSound();
      myDog.animalSound();
      return 0;
    }
            

Output:


The animal's sound
The cat says: meow
The dog says: bow wow

So what's the difference between Inheritence and Polymorphism?


Inheritence, simply passes all the parent class members to the child.

Polymorphism is about decides what form of a method (Class function) to execute.






© Copyright 2022 Advanced PLC. All rights reserved.