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?

Recommended Answers

All 2 Replies

>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 {
public:
  int main() { std::cout<<"Embedded main"<<std::endl; return 0; }
};

int main()
{
  std::cout<<"Global main"<<std::endl;
  A().main();
}

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.

Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.