Studytonight is now part of the GUVI universe. Explore GUVI →
🤩 New Cool Developer Tools for you. Explore →
FREE JavaScript Video Series Start Learning →
Signup/Sign In
Tests
MCQs to test your knowledge.
Compilers
Compilers to execute code in browser.
Index
LAST UPDATED: OCTOBER 31, 2020

C++ Polymorphism Example Program

Hello Everyone!

In this tutorial, we will learn how to implement the concept of Polymorphism, in the C++ programming language.

To understand the concept of Polymorphism in CPP, we will recommend you to visit here: Function Overriding, where we have explained it from scratch.

Code:

#include <iostream>
using namespace std;
//defining the class Addition to overload the method sumOf() to explain the concept of Polymorphism
class Addition {
 public:
 int sumOf(int n1, int n2) {
 cout << "\nPerforming the addition operation on two integers and the value returned is: ";
 return n1 + n2;
 }
 int sumOf(int n1, int n2, int n3) {
 cout << "\nPerforming the addition operation on three integers and the value returned is: ";
 return n1 + n2 + n3;
 }
 int sumOf(int n1, int n2, int n3, int n4) {
 cout << "\nPerforming the addition operation on four integer values and the value returned is: ";
 return n1 + n2 + n3 + n4;
 }
};
//Defining the main method to access the members of the class
int main() {
 cout << "\n\nWelcome to Studytonight :-)\n\n\n";
 cout << " ===== Program to explain the concept of Polymorphism, in CPP ===== \n\n";
 Addition add; //Default constructor is called- which is not required to be written explicitly
 cout << add.sumOf(3, 5) << "\n\n";
 cout << add.sumOf(3, 5, 10) << "\n\n";
 cout << add.sumOf(3, 5, 7, 10) << "\n\n";
 cout << "\n\nExiting the main() method\n\n\n";
 return 0;
}

Output:

C++ polymorphism

We hope that this post helped you develop better understanding of the concept of Polymorphism in C++. For any query, feel free to reach out to us via the comments section down below.

Keep Learning : )



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.

Learn to Code
Learn and practice coding side-by-side.
NEW
C language Course
115+ coding exercises
Javascript Course
85+ coding exercises

AltStyle によって変換されたページ (->オリジナル) /