-1

I was studying an example of Singleton Pattern in c++.

class Singleton
{
    private:
        static Singleton oneandonly;
        Singleton(){};
        ~Singleton(){};
        Singleton(const Singleton &);
        Singleton & operator= (const Singleton &);
    public:
        static Singleton &getInstance(){ return oneandonly; };
}

I do not understand what following line do.

Singleton(const Singleton &);

I always used const for methods but now is for the formal parameter of the method, and the '&' does have any particular meaning or is just an odd name. And then the line: static Singleton &getInstance(){ return oneandonly; }; Why there is a & in front of the method?

4 Answers4

0

It declare the copy constructor private, so that object cannot be copied. See: What's the use of the private copy constructor in c++

Community
  • 1
  • 1
Joky
  • 1,608
  • 11
  • 15
0

You need to buy a book on c++.

C and C++ are two distinct languages that happen to share 13 keywords.

The '&' means 'reference'. Kind of like a pointer but more restrictive.

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
0

That line is a copy constructor which is called when you assign an object to another object of the same type. Since it's declared as private in this case, it means that copy constructor will not be called outside the class. Well, that's the point for a singleton, isn't it?

The '&' on the other hand is called reference. Your copy constructor takes a Singleton reference as a parameter. See this question to understand how reference operator is used.

I recommend reading a C++ book for understanding references and classes in more depth.

Community
  • 1
  • 1
Varaquilex
  • 3,447
  • 7
  • 40
  • 60
0

In a parameter, const means that the method promises not to alter this object. & means that it is a reference.

wvdz
  • 16,251
  • 4
  • 53
  • 90