- C++ Introduction
- C++ Getting Started
- C++ Syntax
- C++ Output (Print Text)
- C++ Comments
- C++ Variables
- C++ Declare Multiple Variables
- C++ Identifiers
- C++ User Input
- C++ Data Types
- C++ Operators
- C++ Strings
- C++ Math
- C++ Booleans
- C++ Conditions
- C++ Switch
- C++ While Loop
- C++ For Loop
- C++ Break And Continue
- C++ Arrays
- C++ References
- C++ Pointers
- C++ Functions
- C++ Function Overloading
- C++ OOP
- C++ Classes And Objects
- C++ Class Methods
- C++ Constructors
- C++ Access Specifiers
- C++ Encapsulation
- C++ Inheritance
- C++ Multilevel Inheritance
- C++ Multiple Inheritance
- C++ Inheritance Access
- C++ Polymorphism
- C++ Files
- C++ Exceptions
- C++ How To Add Two Numbers
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, think of a base class called Animal
that has a method called animalSound()
. Derived classes of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own implementation of an animal sound (the pig oinks, and the cat meows, etc.):
Example
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" ;
}
};
Now we can create Pig
and Dog
objects and override the animalSound()
method:
Example
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;
}
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.
Practice Excercise Practice now
Products
Partner
Copyright © RVR Innovations LLP 2024 | All rights reserved - Mytat.co is the venture of RVR Innovations LLP