Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't we place the C++ main method inside a class?

Tags:

c++

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)?

like image 879
Nir Lanka Avatar asked Jul 10 '12 19:07

Nir Lanka


People also ask

Can you have a main method inside a class?

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".

Why should we enclose main method within a class?

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”.

Can we write main inside class in C++?

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.

Does every class need a main method C#?

It is not necessary for all the classes to have a main method. main method is used as an entry point for java applications.


1 Answers

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.

like image 98
Seva Alekseyev Avatar answered Sep 30 '22 18:09

Seva Alekseyev