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

In C ++, why don't we put the main method inside the class (like Java)? Why doesn't that make sense (I think)?

+6
source share
5 answers

We can. main not a reserved word. But by locale, the C ++ toolchain expects the program's entry point to be main in the global scope. Thus, main inside the class will not be recognized as an entry point to the program.

It is not possible to define a class method named main and call it from the global main .

This design is fully consistent with C. Compatibility with existing C code was the primary goal of developing C ++ early on, and there was hardly any real benefit to changing the entry point agreement. Therefore, they kept the standard C in place. And, as everyone says, C ++, unlike Java, perfectly supports stand-alone (i.e. non-classical) functions.

+21
source

Why us Why do we need to?

For a class method that makes sense, we must have an instance of the object. When main is called, we have no instance.

So a static member function could be made instead, but what's the point? Is this "more object oriented"? How it is?

I think it makes sense, as C ++ does: main is where you start, before you have any objects, before any instances exist.

In Java, main is a static member because nothing exists. But in C ++, there are non-member functions, so why not let main be one of them?

+20
source

Since in C, which precedes classes much, main is a stand-alone function and has not been changed to C ++ for compatibility.

If you really want to do this, it doesn't bother you to write the class that you create in main , and then call the main method.

+10
source

In C ++, main () is a function that is called when the program starts and is not a method. This main function can use classes and class methods in its execution.

Methods are functions defined in classes that must remain close to the class / object in which they are defined. Therefore, main () does not get stuck inside the class, because it is not designed to work with one class or object

+2
source

C ++ was intended and should be backward compatible with C and cfront (the first C ++ compiler) would not work if main were not allowed.

The first / original C ++ compiler, called cfront, compiled C ++ by converting this to C, and C requires the use of main ()

For more information, see the following URL:

http://en.wikipedia.org/wiki/Cfront

http://www.physics.drexel.edu/courses/Comp_Phys/General/C_basics/

+2
source

Source: https://habr.com/ru/post/920153/


All Articles