C++ Polymorphism C-PLUS-PLUS

C++ Polymorphism  

C++ Polymorphism

C++ Polymorphism

Polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance.

Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance.

C++ polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function.

Example

#include <iostream>
#include <string>
using namespace std;

// Base class
class Animal {
  public:
    void animalSound() {
      cout << "The animal makes a sound \n" ;
    }
};

// Derived class
class Pig : public Animal {
  public:
    void animalSound() {
      cout << "The pig says: wee wee \n" ;
    }
};

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

int main() {
  Animal myAnimal;
  Pig myPig;
  Dog myDog;

  myAnimal.animalSound();
  myPig.animalSound();
  myDog.animalSound();
  return 0;
}
 

Output:

The animal makes a sound
The pig says: wee wee
The dog says: bow wow

Why And When To Use "Inheritance" and "Polymorphism"?

 It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.

Download free E-book of C-PLUS-PLUS


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries