Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Can main Be Overloaded in C++



In every C/C++ program, execution starts from the main() function. Defining multiple main() functions will result in a compilation error.

Can main() be Overloaded in C++?

No, we cannot overload the main() function in C++ because main() serves as the entry point of any C++ program and must follow a predefined prototype.

While C++ does support function overloading (i.e., multiple functions with the same name but different parameters), this does not apply to the main() function. If you try to create multiple main() functions will result in a compilation error due to invalid overloading.

The following are the only two valid prototypes of the main() function:

// Declaration of main() function 
// without argument
int main();                    
// Declaration of main() function 
// with command-line argument        
int main(int argc, char* argv[]);     

Example of Invalid Overloading of main()

The following example demonstrates what happens if you try to attempt an invalid overloading of main() function:

#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);
}

The above program display the following result:

main.cpp:3:5: warning: 'int main(int)' takes only zero or two arguments
main.cpp:7:5: warning: first argument of 'int main(char*)' should be 'int'
main.cpp:7:5: warning: 'int main(char*)' takes only zero or two arguments
main.cpp:7:5: error: conflicting declaration of C function 'int main(char*)'
...
...
...

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

Example of main() without Overloading

Following is the illustration of the program based on the above statement:

#include<iostream>
using namespace std;

class my_class {
   public:
      int printValue(int x) {
         cout << "Value of x: " << x << "\n";
         return 0;
      }

      int printValue(const char *y) {
         cout << "Value of string y: " << y << "\n";
         return 0;
      }

      int printValues(int x, int y) {
         cout << "Value of x and y: " << x << ", " << y << "\n";
         return 0;
      }      
};

int main() {
   my_class obj;
   obj.printValue(10);
   obj.printValue("Hello");
   obj.printValues(15, 25);
   return 0;
}

The above code obtained the following result:

Value of x: 10
Value of string y: Hello
Value of x and y: 15, 25
Updated on: 2025-06-03T14:17:49+05:30

729 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements