Since C+++ allows function overloading, can we overload main()
?
For example,
int main(const std::string &)
{
return 0;
}
int main(int argc, char *argv[])
{
return main("calling overloaded main");
}
gcc-4.3.4
doesn't compile this, and gives these errors: (see at ideone)
prog.cpp:4: error: first argument of ‘int main(const std::string&)’ should be ‘int’
prog.cpp:4: error: ‘int main(const std::string&)’ takes only zero or two arguments
prog.cpp: In function ‘int main(int, char**)’:
prog.cpp:8: error: declaration of C function ‘int main(int, char**)’ conflicts with
prog.cpp:4: error: previous declaration ‘int main(const std::string&)’ here
prog.cpp: In function ‘int main(int, char**)’:
prog.cpp:10: error: invalid conversion from ‘const char*’ to ‘int’
prog.cpp:8: error: too few arguments to function ‘int main(int, char**)’
prog.cpp:10: error: at this point in file
So I'm wondering if the C++ Standard explicitly forbids overloading of main
? If so, which statement?
Yes, we can overload the main method in Java, but When we execute the class JVM starts execution with public static void main(String[] args) method.
The main() function can be overloaded in C++ by defining main as member function of a class. Since main is not a reserved word in many programming languages like C++,C# ,java etc, main can be declared as a variable or member function.
Here a question arises that like the other methods in Java, can we also overload the main() method. The answer is, yes, we can overload the main() method. But remember that the JVM always calls the original main() method. It does not call the overloaded main() method.
You can't have two main()s.
Yes it explicitly forbids that. Refer to 3.6.1p2
An implementation shall not predefine the main function. This function shall not be overloaded.
This way, the main function's name can stay unmangled. That is, the runtime library can call a symbol having a fixed name (e.g main
or _main
) to jump to the main function. The libraries' code will not need to depend on what parameter list the program's main
function has.
The implementation is also allowed to define additional valid parameter lists for the main
function (The POSIX spec specifies a char **env
parameter for the environment variables, for example). It would not be clear when an overload of main
is a "non-main function" or whether it's a "main function", thus an entry point. Presumably, you would want to get an error if you would declare more than one entry point, so such issues are important.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With