proper initialization

B

bob

Let's say that a class only allows proper initialization through
its constructor. Let's also say that you need a global variable of
that class,
but you can't initialize it at the beginning of the program.

What is the most practical solution?
 
A

Alf P. Steinbach

* (e-mail address removed):
Let's say that a class only allows proper initialization through
its constructor. Let's also say that you need a global variable of
that class,
but you can't initialize it at the beginning of the program.

What is the most practical solution?

At the risk of sounding like I'm bashing you, the most practical
solution is to _not_ use global variables, especially for a newbie.

See the FAQ about global variables.

Summary: they're evil.
 
V

Victor Bazarov

Let's say that a class only allows proper initialization through
its constructor. Let's also say that you need a global variable of
that class,
but you can't initialize it at the beginning of the program.

What is the most practical solution?

There is none. Global variables get initialised at the beginning, before
even 'main' is called. If you can't allow that, you're out of luck. Your
alternative is a singleton, which can be initialised at the first use (and
not necessarily at the beginning of the program), but then you're stuck
with using a function to obtain a pointer or a reference to that object:

class myPseudoGlobalVar {
...
public:
myPseudoGlobalVar(arguments);
void whatever();
};

static myPseudoGlobalVar& get_myPseudoGlobalVar() {
static myPseudoGlobalVar var(<initialise here>);
return var;
}

...
get_myPseudoGlobalVar().whatever();

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top