1

When I was learning the singleton pattern, I saw that the constructor is private, so can static class member variables still be initialized with new()?

#include <iostream>
using namespace std;

class A{
public:
    static A* getInstance(){
        return aa;
    }
    void setup(){
        cout<<"inside setup!"<<endl;
    }
private:
    static A* aa;
    A(){
        cout<<"constructor called!"<<endl;
    }
};
A* A::aa = new A;   //  <== How to explain this sentence ???                                                                                    

int main()
{
    A* aa1 = A::getInstance();
    A* aa2 = A::getInstance();

    if(aa1 == aa2)
        cout<<"Yes"<<endl;
    else
        cout<<"No"<<endl;
    cout << "Hello world!"<<endl;
    return 0;
}
Leon
  • 11
  • 1

1 Answers1

2

According to the C++11 standard, specifically in 9.4.2 [class.static.data]:

  1. [...] The initializer expression in the definition of a static data member is in the scope of its class [...]

So the reason why you are able to do

A* A::aa = new A;

from "outside" the class declaration, is because new A (the initializer expression) is performed in the scope of A, and therefore has access to all private, protected and public identifiers of that class, including the private constructor.


As a note, please rethink your singleton design. Your class is not properly destroyed, can be copied/moved and returns a pointer for no good reason. Consider using something like this, instead.

Also, please avoid using namespace std.

LHLaurini
  • 1,737
  • 17
  • 31