In C++ why don't we ever place the main method inside a class (like Java)? Why doesn't doing so make sense (I think)?
The main() method can appear in any class that is part of an application, but if the application is a complex containing multiple files, it is common to create a separate class just for main(). The main class can have any name, although typically it will just be called "Main".
Main method is the entry point of the execution in Java. When we execute a class JVM searches for the main method and execute the contents of it line by line. If you observe the following example you can compile a this program but if you try to execute it you will get an error saying “Main method not found”.
Writing a class named main is not allowed generally in C++, as the compiler gets confused it with main() method. Hence when we write the main class, creating its object will lead to error as it won't consider the 'main' as a class name.
It is not necessary for all the classes to have a main method. main method is used as an entry point for java applications.
We can. main
is not a reserved word. But by the language standard, the C++ toolchain expects the entry point of the program to be main
in the global scope. So the main
inside a class won't be recognized as the program's entry point.
Feel free to define a class method called main
, and call it from the global main
.
This design comes all the way from C. Compatibility with existing C code was a major design goal of C++ early on, and there was hardly any real benefit to changing the entry point convention. So they kept the C standard in place. And like everyone said, C++, unlike Java, does perfectly allow for standalone (i. e. non-class) functions.
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