🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to C++ Notes
Topic #98

C++ Polymorphism


Polymorphism

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

Like we specified in the previous chapter; Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways.

For example, imagine a base class Animal with a method called makeSound(). Derived classes of Animals could be Pigs, Cats, Dogs, Birds, etc. Every animal can "make a sound", but each one sounds different:

  • Pig: wee wee
  • Dog: bow wow
  • Bird: tweet tweet

This is polymorphism - the same action (making a sound) behaves differently for each animal:

Example

// 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";
    }
};

Note: Remember from the Inheritance chapter that we use the : symbol to inherit from a class.

Now we can create Pig and Dog objects and override the animalSound() method:

Example

// 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;
}

Note: 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.

Want to go beyond the notes?

Join CodingNow 2.0's C++ course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

C++ Polymorphism – FAQs

Quick answers about learning C++ Polymorphism in C++.

This free note from CodingNow 2.0 explains C++ Polymorphism in C++ — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every C++ topic on CodingNow 2.0, including C++ Polymorphism, is 100% free with no signup required.
With focused practice, most students grasp C++ Polymorphism in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now