Daniel February 2016

Undefined reference to Singleton::Singleton()

I'm trying to get the first basic singleton example from Design Patterns working, but this has me stumped.

This code compiles cleanly with g++ -c Singleton.cpp:

class Singleton {
public:
    static Singleton* Instance();
protected:
    Singleton();
private:
    static Singleton* _instance;
};

Singleton* Singleton::_instance = 0;

Singleton* Singleton::Instance() {
    if (_instance == 0) {
        _instance = new Singleton;
    }
    return _instance;
}

But when I add a skeletal main() and compile with g++ Singleton.cpp I get undefined reference to 'Singleton::Singleton()'.

What am I missing?

Answers


NathanOliver February 2016

You never added a definition for

Singleton();

Which is used in Singleton* Singleton::Instance() by

_instance = new Singleton;

Typically you should you can layout a singleton like:

class Singleton {
public:
    static Singleton* Instance() { static Singleton s; return &s; }
    Singleton(const Singleton&) = delete;
    void operator=(const Singleton&) = delete;
private:
    Singleton() = default;
};

Post Status

Asked in February 2016
Viewed 3,499 times
Voted 8
Answered 1 times

Search




Leave an answer