Why don't we place the C++ main method inside a class?
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.
Why would we? Why do we need to?
For a class method to make sense, we have to have an instance of an object. When main
is called, we don't have an instance.
So it could have been made a static member function instead, but what would be the point? Is it "more object-oriented"? How so?
I think it makes good sense the way C++ does it: main
is where you start before you have any objects, before any instances exist.
In Java, main
is a static member because nothing else exists. But in C++, non-member functions exist, so why not let main
be one of those?
Because in C which far predates classes, main
was a standalone function and that wasn't changed in C++ to maintain compatibility.
If you really want to do this, there's nothing stopping you from writing a class you instantiate in main
and then call a main
method upon.