Signup/Sign In
LAST UPDATED: OCTOBER 31, 2020

C++ Method Overloading Program

Hello Everyone!

In this tutorial, we will learn how to demonstrate the concept of Method Overloading, in the C++ programming language.

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

Code:

#include <iostream>

#include <vector>

using namespace std;

//defining the class shape to overload the method area() on the basis of number of parameters.
class shape {

    //declaring member variables
    public:
        int l, b, s;

    //defining member function or methods
    public:
        void input() {
            cout << "Enter the length of each side of the Square: \n";
            cin >> s;
            cout << "\n";
            cout << "Enter the length and breadth of the Rectangle: \n";
            cin >> l >> b;
            cout << "\n";
        }

    //Demonstrating Method Overloading
    public:
        void area(int side) {
            cout << "Area of Square = " << side * side;
            cout << "\n";
        }

    void area(int length, int breadth) {
        cout << "Area of Rectangle = " << length * breadth;
        cout << "\n";
    }
};

//Defining the main method to access the members of the class
int main() {
    cout << "\n\nWelcome to Studytonight :-)\n\n\n";
    cout << " =====  Program to demonstrate Method Overloading in a Class, in CPP  ===== \n\n";

    //Declaring class object to access class members from outside the class
    shape sh;

    cout << "\nCalling the input() function to take the values from the user\n";
    sh.input();

    cout << "\nCalling the area(int) function to calculate the area of the Square\n";
    sh.area(sh.s);

    cout << "\nCalling the area(int,int) function to calculate the area of the Rectangle\n";
    sh.area(sh.l, sh.b);

    cout << "\nExiting the main() method\n\n\n";

    return 0;
}

Output:

C++ method overloading

We hope that this post helped you develop a better understanding of the concept of Method Overloading 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.