Hi

I wrote a Singleton class but i got an error while controlling instantiation

captain.h

#ifndef CAPTAIN_H
#define CAPTAIN_H

#include <iostream>
#include <string>

class Captain
{
private:
    Captain();
    Captain(const Captain&);
    Captain &operator=(const Captain&);

    std::string name;

public:
    //Controll Instantiation
    static Captain &GetInstance();

    //Set Name of the Captain
    std::string GetName();

    //Get his/her name
    void SetName(std::string _name);

};

#endif // CAPTAIN_H

captain.cpp

#include "captain.h"

Captain& Captain::GetInstance(){
    static Captain instance; //The Error redirect me to here.
    return instance;
}

std::string Captain::GetName(){
    return name;
}

void Captain::SetName(std::string _name){
    name = _name;
}

main.cpp

#include <iostream>
#include "captain.h"


int main()
{

    Captain &Club = Captain::GetInstance();
    Club.SetName("Sarbast");
    std::cout<<Club.GetName()<<std::endl;

    return 0;
}

Error

error: undefined reference to `Captain::Captain()'

Why is a captian a singleton? Are there not multiple captains in the world? If you want to make a singleton then you need to follow the correct syntax. Here is an example of a singleton:

class Singleton
{
public:
    // this is a lazy evaluated singleton
    Singleton GetInstance()
    {
        static Singleton instance;
        return instance;
    }
private:
    Singleton() {};  // code for constructor goes here
    // make sure these are here to stop the object from being copied
    Singleton(const Singleton &);
    void operator=(const Singleton &);
}

Edited 2 Years Ago by NathanOliver

Well i know there are its just a name i chose randomly and its only for training not actual project :D
and i know the constructor and copy cnstructor should be private.

I think my code is same as the one you wrote. i just seperated the function definations and declarations.

Ops I forgot constractor defination in the captain.cpp :-D

Thank you it was the error :)

In your header file, you promised that you would be writing the default constructor. Like this:

Captain();

So because you made that promise, you have to write a default constructor of this form:

Captain::Captain()
{

}

but you didn't. So the compiler complains that it can't find the default constructor that you promised you would write.

This question has already been answered. Start a new discussion instead.