log
and engine
are totally separate. Neither has access to the other inherently.
If you want engine
to be able to access an instance of Logfile
, you could for example pass it into engine
via a setter or via Engine
's constructor:
Engine::Engine(Logfile& log) {
log.entry("Engine constructed");
}
There are alternatives where you can have a global instance of Logfile
(outside the scope of main
). Generally global variables are a bad idea; variables' lifetimes should be reduced to the smallest scope possible. However, a logfile might qualify as a reasonable exception to this rule.
To explain a little further, you could use a singleton for the logfile. Using singletons is a highly contentious issue; just search for singletons or double-checked locking and you'll find ample discussions on the perils.
However, things have become a good bit safer with the advent of C++11. The new standard guarantees that initialization of a local static object is threadsafe. This allows us to do something like the following:
class Logfile {
public:
static Logfile& instance();
void entry(const string& value) { cout << value << '\n'; }
private:
Logfile() { cout << "OPENED\n"; }
~Logfile() { cout << "CLOSED\n"; }
};
Logfile& Logfile::instance() {
static Logfile log_file;
return log_file;
}
Note that the constructor is now private. The only way to get a Logfile
is via the instance()
function, and since it has a local static Logfile
, there will only ever be that one instance.
You can then use it inside Engine()
like:
Engine::Engine() {
Logfile::instance().entry("Engine constructed");
}
You still need to be careful here though. For example, at this point in time, VC2012 still hasn't implemented the threadsafe initialization of local statics as required by C++11.