Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function outside main () [duplicate]

Tags:

c++

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?

like image 434
Flavius Ibanescu Avatar asked Jan 26 '26 05:01

Flavius Ibanescu


1 Answers

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";
}
like image 159
Some programmer dude Avatar answered Jan 27 '26 19:01

Some programmer dude