How to pass argument in a singleton

argument-passing, c++, singleton

Solution

You don't need to allocate the instance of singleton dynamically. It could look the following way (this is sometimes called "lazy loading singleton" ~ the instance is created late & kinda "automatically"):

#include <iostream>
#include <string>

class Questionnary
{
private:
    // constructor taking string:
    Questionnary(const std::string& name) : name_(name) { }
public:
    static Questionnary& getInstance(const std::string& name)
    {
        static Questionnary q(name);
        std::cout << "My name is: " << q.name_ << std::endl;
        return q;
    }
private:
    std::string name_;
};

int main() {
    Questionnary::getInstance("Josh");
    Questionnary::getInstance("Harry");
}

output:

My name is: Josh
My name is: Josh

Note that constructor will be called only once right when the `getInstance` is called for the first time.

Problem

I've been wondering how to pass argument to a singleton contructor. I already know how to do a singleton, but I've been unlucky to find a way to do it. Here is my code (part of it). ``` Questionnary* Questionnary::getInstance(){ static Questionnary *questionnary = NULL; if(questionnary == NULL){ cout << "Object created"; questionnary = new Questionnary(); } else if(questionnary != NULL){ cout << "Object exist"; } return questionnary; } Questionnary::Questionnary(){ cout << "I am an object"; } //This is want i want to acheive Questionnary::Questionnary(string name){ cout << "My name is << name; } ``` Many thanks in advance (BTW i know how and why a singleton is bad)

Original source

Related problems