C++ Polymorphism C-PLUS-PLUS
- C++ Introduction
- C++ Syntax
- C++ Output (cout <<)
- C++ Comments
- C++ Variables
- C++ User Input
- C++ Data Types
- C++ Operators
- C++ Strings
- C++ Math
- C++ Booleans
- C++ If Else
- C++ Switch
- C++ While Loop
- C++ Do/While Loop
- C++ For Loop
- C++ Break and Continue
- C++ Arrays
- C++ References
- C++ Pointers
- C++ Functions
- C++ Functions Parameters
- C++ Function Overloading
- C++ OOP
- C++ Classes and Objects
- C++ Class Methods
- C++ Constructors
- Destructors in C++
- C++ Access Specifiers
- C++ Encapsulation
- C++ Inheritance
- C++ Polymorphism
- C++ Files
- C++ Exception Handling
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.