Can main() be overloaded in C++?


In C++, we can use the function overloading. Now the question comes in our mind, that, can we overload the main() function also?

Let us see one program to get the idea.

Example

#include <iostream>
using namespace std;
int main(int x) {
   cout << "Value of x: " << x << "\n";
   return 0;
}
int main(char *y) {
   cout << "Value of string y: " << y << "\n";
   return 0;
}
int main(int x, int y) {
   cout << "Value of x and y: " << x << ", " << y << "\n";
   return 0;
}
int main() {
   main(10);
   main("Hello");
   main(15, 25);
}

Output

This will generate some errors. It will say there are some conflict in declaration of main() function

To overcome the main() function, we can use them as class member. The main is not a restricted keyword like C in C++.

Example

#include <iostream>
using namespace std;
class my_class {
   public:
      int main(int x) {
         cout << "Value of x: " << x << "\n";
         return 0;
      }
      int main(char *y) {
         cout << "Value of string y: " << y << "\n";
         return 0;
      }
      int main(int x, int y) {
         cout << "Value of x and y: " << x << ", " << y << "\n";
         return 0;
      }      
};
int main() {
   my_class obj;
   obj.main(10);
   obj.main("Hello");
   obj.main(15, 25);
}

Output

Value of x: 10
Value of string y: Hello
Value of x and y: 15, 25

Updated on: 30-Jul-2019

513 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements