2

I'm trying to do this:

#include <iostream>
using namespace std;

class smth {
  public:
  void function1 () { cout<<"before main";}
  void function2 () { cout<<"after main";}
};

call function1();

int main () 
{
  cout<<" in main";
  return 0;
}
call funtion2();

and i want to have this message: " before main" " in main" "after main"

How can I do it?

Deidrei
  • 2,125
  • 1
  • 14
  • 14

1 Answers1

10

You can't. At least not that way. You should be able to solve it by putting the code in a class constructor and destructor, then declaring a global variable:

struct myStruct
{
    myStruct() { std::cout << "Before main?\n"; }
    ~myStruct() { std::cout << "After main?\n"; }
};

namespace
{
    // Put in anonymous namespace, because this variable should not be accessed
    // from other translation units
    myStruct myStructVariable;
}

int main()
{
    std::cout << "In main\n";
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • OK, it's working ... But i don't understand how the destructor is being called. And why using namespace? I never get what namespace is using for... – Flavius Ibanescu Dec 05 '13 at 12:54
  • @FlaviusIbanescu Global and static variables are initialized before `main` is called, and destructed after `main` returns. Having global variables in an anonymous namespace (like I do) is equivalent to making the the global variables `static`, i.e. they are not exported from the current translation unit. – Some programmer dude Dec 05 '13 at 12:57
  • The RT (for RunTime) library do handle static destruction at program exit. On windows/visual studio it is "msvcrtXX.dll" where "XX" is the Visual Studio version number. – Johan Dec 05 '13 at 12:57
  • @FlaviusIbanescu Namespaces in general is for scoping. For example all standard library classes and functions are in the `std` namespace. This means that you can easily declare a variable named `vector` and it will not collide with `std::vector`. – Some programmer dude Dec 05 '13 at 12:58