Dean Dean - 1 year ago 74
C++ Question

Where is a static local variable object of function defined?

I know that static member variables have to be defined out of the class somewhere (not in a header - in a TU), but I'm wondering then why the following works

#include <iostream>

class Logger {
static const Logger& GetInstance() {
static Logger logger; // ??
return logger;

void hello() const {
std::cout << "Hello";

Logger() {


const Logger& logger = Logger::GetInstance();

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


return 0;

Where is the object associated with
defined? And why doesn't a function static variable require a definition/instantiation point as for a static class member variable?

Answer Source

You do define it: in the function GetInstance().

It's just that luck is on your side: that function is only encountered in exactly one translation unit (you've put the class definition in a source file), so the linker is not going to moan.

It would have been a different matter if the code were in a header and included in more than one translation unit.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download