MOCKSTACKS
EN
Questions And Answers

More Tutorials








C++ Polymorphism

The definition of polymorphism is "many forms", and it occurs when we have superclass and multiple childs class related to each other by inheritance.

Polymorphism is nothing but overriding a function or method from superclass in child classes. you can look at picture below to understand it:

C++ Polymorphism

To learn more about Polymorphism, jump to C++ Function Overriding

In this section you will learn about overriding function, example getColorAsMessage()

Example in C++ Overriding

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

class Vehicle {
 public:              
    string color;        
    string make;         
    string model;
 public:             
    string getColorAsMessage() { 
      return "My color is: " + color;
    }
};

class Car : public Vehicle {     

 public:             
    string getColorAsMessage() {  // Method Overriding
      return "The Car color is: " + color; // Original Method in Vehicle class print My color is:...
  }
};

class Truck : public Vehicle {    

 public:             
    string getColorAsMessage() { // Method Overriding
      return "The Truck color is: " + color;  // Original Method in Vehicle class print My color is:...
  }
};


int main() {

  // Car section
  Car newCar;  
  newCar.color = "Red";
  newCar.make = "BMW";
  newCar.model = "X5";
  cout << newCar.getColorAsMessage() << "\n"; 
  cout << newCar.make << "\n"; 
  
  // Truck section
  Truck newTruck;  
  newTruck.color = "White";
  newTruck.make = "Chevy";
  newTruck.model = "Silverado";
  cout << newTruck.getColorAsMessage() << "\n"; 
  cout << newTruck.make << "\n"; 

  return 0;
}

Output

The Car color is: Red
BMW
The Truck color is: White
Chevy

Conclusion

In this page (written and validated by ) you learned about C++ Polymorphism . What's Next? If you are interested in completing Cpp tutorial, your next topic will be learning about: Cpp Class Constructor.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.