1

I want to write a little Singleton class that looks like:

#include <vector>

class Interpreter {

private:
    static Interpreter* interInstance;
    Interpreter() {}

public:
    static Interpreter* getInstance();
    ~Interpreter() {}

};

Interpreter* Interpreter::interInstance = 0;

Interpreter* Interpreter::getInstance(){
if (!interInstance)
    interInstance = new Interpreter();

return interInstance;
}

But this will produce this exception:

multiple definition of `Interpreter::getInstance()

This error can be corrected by wrapping the class and the function in one namespace. But I don't really understand why I need a namespace. There is one declaration of getInstance() and one implementation, no?

4
  • 3
    If you are including this code from several translation units, then there are several implementations of getInstance() and interInstance Commented May 15, 2012 at 19:11
  • 1
    Adding on, you should always wrap your headers in a header guard. Commented May 15, 2012 at 19:13
  • Are you using an anonymous namespace, i.e. namespace { /* stuff */ }? Commented May 15, 2012 at 19:20
  • yes, over the whole file Commented May 15, 2012 at 19:27

1 Answer 1

2

Move the definition outside the header, in an implementation file, for both the member initialization and the method:

Interpreter.h

class Interpreter {

private:
    static Interpreter* interInstance;
    Interpreter() {}

public:
    static Interpreter* getInstance();
    ~Interpreter() {}

};

Interpreter.cpp

#include "Interpreter.h"
Interpreter* Interpreter::interInstance = 0;

Interpreter* Interpreter::getInstance(){
if (!interInstance)
    interInstance = new Interpreter();

return interInstance;
}

Inside a class or struct definition, static doesn't give symbols internal linkage as it does outside, so you're breaking the one definition rule.

If multiple translation units include a header that contains non-inline methods or define the same symbol, you'll run into multiple definition.

Sign up to request clarification or add additional context in comments.

1 Comment

It might be worth adding a pointer to some larger description of the many inconsistent meanings of "static" in C++, but I think that one-line explanation is as good as anyone's ever going to do in one sentence.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.