Sign in to follow this  

Calling static methods before main() (in the global scope)

Recommended Posts

I've a class named SessionConfig which has a static method called setSessPath. and I want to call it before main() (e.g. in the global scope) to change the default configuration.
#include "sessionconfig.h"

using std::cout;
using std::endl;

class SessionConfig;

SessionConfig::setSessPath("/tmp/session");//setSessPath() is a static method

int main(int argc, char *argv[]){.....}

but this gives me parse error
 error: expected constructor, destructor, or type conversion before ‘(’ token
Edit: also I've the same Code SessionConfig::setSessPath("/tmp/default-sess-path") in the sessionconfig.cpp file (instead of string SessionConfig::sessPath = "/tmp/cgi++/sess";) to initialize the member variable through the setter which also yields the same error. I didnt know that its not possible to make a function call from global scope am I right ??

Share this post

Link to post
Share on other sites
You cannot execute statements at global scope. Of course, you can still define a global variable and put the code you want to execute in its constructor. However, you can't execute anything with certainty before main() is called: there is not guarantee that the global variable will be initialized before main(), you only know that it's going to be initialized before it's used (and even then, you have to be careful with using it from the constructor of another global variable).

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this