Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Smita Kapse

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

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.