Tuesday, July 14, 2009

C++. How to use main() in a class? Is it possible?

Is it possible to use the pure object-oriented programming in C++?





Is it possible to redefine the entry point of a program to a member function?





e.g. the next code will not compile:


#include %26lt;cstdlib%26gt;


#include %26lt;iostream%26gt;





using namespace std;





class MyClass


{


  public:


    static int main(){


      //This is the main function... it should be


      //the entry point


      system("PAUSE");


      return EXIT_SUCCESS;


    }


};

C++. How to use main() in a class? Is it possible?
Good question.





"Is it possible to redefine the entry point of a program to a member function?"


Yes, but it's not quite what you are expecting, and you really don't want to do something like that. A global main() function is required by the standard. In other words, if you wish to write standards compliant code, you should be using a global main, not a custom entry point. But to explain:





main() is not the entry point. Actually, a function called mainCRTStartup is. You're asking yourself now, I've never written a mainCRTStartup, and that's correct. It's part of the code supplied with the compiler. One part of the code is mainCRTStartup, which is the entry point. mainCRTStartup, among other things, calls main(). Don't believe me? Use the linker options to leave out the default libs; for VC++ it's /NODEFAULTLIB and for gcc linker it is -nodefaultlibs -nostdlib. You'll be forced to write mainCRTStartup yourself.





Now, technically you could change the entry point to MyClass::main()., but then you would have to reimplement the code in mainCRTStartup yourself. For what point?





"e.g. the next code will not compile:"


Just to nitpick, technically the code will compile, but it won't link to an executable, since you need the appropriate entry points defined in some linked in binary.





Aside, to correct answerer "the chip": "C++ isn't object-oriented, it's procedure-driven. The two programming concepts don't really mix."


C++ is object oriented. It has some very powerful generic programming syntax not present in other languages. Feel free to read Modern C++ Design http://www.amazon.com/Modern-C%2B%2B-Des... before complaining about C++ not being OO. Also, object-oriented and procedural programming mix just fine. Any reason they don't?
Reply:No, you can't do that in C++. It always looks for a global main function.
Reply:i dont think its possible to put main( ) inside any declared class.The main( ) fct is a fct declared inside the iostream library of c++, and u cannot use it inside any class,but it is used apart
Reply:C++ isn't object-oriented, it's procedure-driven. The two programming concepts don't really mix. If you want to do object oriented programming you need something like java.

cyclamen

No comments:

Post a Comment