Can the main() call be embedded within a class? At work yesterday I caught a snippet somewhere, and I noticed main() was inside a class, something like the following:

[B]class[/B] personnel
     [B]void[/B] in_prev_data();
     [B]void[/B] in_new_data();

     [B]int[/B] main( [B]int[/B] argc, [B]const char[/B] **argv );

     [B]void[/B] process_data();
     [B]void[/B] pack_data();
     [B]void[/B] save_data();

Wish I had written the address down, so I could of duplicated it here exactly as it was, but that code should be close. Now if this embedding is possible, is someone able to clear it up a little for me, about how it works?

>Can the main() call be embedded within a class?
You need to make the distinction between a function declaration, a function definition, and a function call. What your example does is declare a member function with the same signature as the global main. However, it's not the same function as the global main. Even if you do this, you still need to define a global main as the entry point for your program:

#include <iostream>

class A {
  int main() { std::cout<<"Embedded main"<<std::endl; return 0; }

int main()
  std::cout<<"Global main"<<std::endl;

The reason this is legal is because the member function main is in a different namespace than the global main, so they can both coexist in the same program. How smart this is is debatable though since it can cause confusion.

Okay, didn't look at it that way. Since it is a member of a class it's just another name for an object's function. I don't plan on implementing this type of funciton naming, it just caught my attention as soon as I came across it.


This article has been dead for over six months. Start a new discussion instead.