0
#include <iostream>
using namespace std;

class singleton_p
{
    static singleton_p *instance;

    singleton_p() {};

    //copy constructor
    singleton_p(const singleton_p & b);
    
    singleton_p& operator= (const singleton_p & A);

public:
    static singleton_p & create_instance()
    {
        if(!instance)
        {
            instance=new singleton_p();
        }
        return *instance;
    }
    void display()
    {
        std::cout<<"singleton class display func called\n";
        cout<<(this)<<endl;
        cout<<"---------------------------------"<<endl;
    }
};
singleton_p* singleton_p::instance = NULL;

int _tmain(int argc, _TCHAR* argv[])
{
    singleton_p p1=singleton_p::create_instance();
    p1.display();

     // creating  instance
    singleton_p p2=singleton_p::create_instance();       
    p2.display();

    return 0;
}

I have also made copy constructor and assignment operator private to avoid creating new instance using them. I am defining here singleton class. But it's giving me error in

singleton_p p1=singleton_p::create_instance();

singleton_p p2=singleton_p::create_instance();

  • error C2248: 'singleton_p::singleton_p' : cannot access private member declared in class 'singleton_p' 1>
  • projects\singleton_class\singleton_class\singleton_class.cpp(15) : see declaration of 'singleton_p::singleton_p' 1>
  • projects\singleton_class\singleton_class\singleton_class.cpp(9) : see declaration of 'singleton_p'

Please help me where I am doing wrong. Thanks

Community
  • 1
  • 1
  • Shouldn't `singleton_p* singleton_p::instance = NULL;` be inside the class (and static?)? – Stefan Feb 11 '16 at 09:50
  • Check first line of class definition, the line you pointed out is for initialization of static variable : static singleton_p* instance. – Parvin Kumar Feb 11 '16 at 09:58
  • 3
    You `create_instance` method returns a reference, that you are assigning to a object of type `singleton_p`. So the copy constructor is invoked. Change your `singleton_p p1` to `singleton_p& p1` – mkaes Feb 11 '16 at 09:58
  • Thanks it worked. @mkaes – Parvin Kumar Feb 11 '16 at 10:01
  • Also, using pointer return type is not a good. How can you make sure that it is not deleted undesirably. To ensure that it is created once and deleted once define instance local static. See http://stackoverflow.com/questions/1008019/c-singleton-design-pattern – jaaw Feb 11 '16 at 10:14

0 Answers0