1

I have no idea why this is happening, I followed the example posted here.

class Song {

private:
    // singletong
    Song();
    Song(Song const&); // don't implement
    void operator = (Song const&); //don't implement

public:
    // Singleton method
    static Song &getInstance(){
        static Song song;
        return song;
    }

};

If I don't call the class, there's no problem. As soon as I call the Song class like this:

Song::getInstance();
// also tried: Song &song = Song::getInstance();

Xcode doesn't want to build the project anymore. I'm getting this error: enter image description here

Any ideas why this is happening?

Community
  • 1
  • 1

3 Answers3

8

Your not implementing the constructor which has to exist since your instantiating an object in the getInstance() function:

static Song song;

Either implement it inline (unprefered):

private:
    // singletong
    Song() {
        // Your implementation goes here
    }

Or implement it in a compilation unit (e.g Sound.cpp) (prefered):

Song::Song(){
    // Your implementation goes here
}
Sebastian Hoffmann
  • 11,127
  • 7
  • 49
  • 77
1

Either

  • you didn't implement the default constructor - just replace Song(); with Song() {} to see if this is the cause.
  • you're creating a copy by calling Song s = Song::getInstance() instead of Song& s = Song::getInstance().
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
1

You've not provided an implementation for the default constructor. That is why you get an undefined reference.

This is a link error, not a compiler error. This means that your code has actually compiled correctly. After compilation, the linker takes your compiled object code and "links" it together to form an executable. If all of your functions do not exist like you've declared them to, the linker gets mad (this is not strictly true in the case of dynamic linking, but that's for another question).

However, many compilers will not waste time attempting to link functions that are never called in code.

In your case, you don't get this error when you don't call the function because your getInstance() never attempts to construct an object because it is not being called.

San Jacinto
  • 8,774
  • 5
  • 43
  • 58