Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we overload main() function in C++? [duplicate]

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?

like image 393
Nawaz Avatar asked Mar 12 '11 11:03

Nawaz


People also ask

Can main () be overloaded?

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.

Can we overload main method in C?

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.

Can main () be overloaded justify?

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.

Can you have 2 INT mains?

You can't have two main()s.


1 Answers

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.

like image 119
Johannes Schaub - litb Avatar answered Oct 08 '22 10:10

Johannes Schaub - litb