0

Singleton doubt: how am I able to access a private static object in global space? Code is given below. This runs perfectly fine.


#include <iostream>
using namespace std;

class Singleton {
    static Singleton s;
    static void func()
    {
        cout<<"i am static function "<<endl;
    }
    int i;
    Singleton(int x) : i(x) {
    cout<<"inside Constructor"<<endl;
    }
    void operator=(Singleton&);
    Singleton(const Singleton&);
    public:

    static Singleton& getHandle() {
        return s;
    }
    int getValue() { return i; }
    void setValue(int x) { i = x; }
};

Singleton Singleton::s(47);


int main() {

    Singleton& s = Singleton::getHandle();
    cout << s.getValue() << endl;
    Singleton& s2 = Singleton::getHandle();
    s2.setValue(9);
    cout << s.getValue() << endl;
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322

2 Answers2

1

You can't. Private members are private, no matter the context. You can't access them from anywhere except from inside the class.

What you're doing is not actually accessing the private member directly, you use a public function to return a reference to it which can then be used. The code in the main function does not access the private member m.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

I don't see any thing outside of Singleton accessing the private static variable s.

In main, you have a reference to a Singleton that happens to be named s, but this is not directly accessing the private static variable Singleton::s. Your method Singleton::getHandle returns a reference to Singleton::s that happens to get bound to the s in main, but as you demonstrate, you can bind this to something other than s, like s2.

The line

Singleton Singleton::s(47);

is defining (was well as initialing) Singleton::s, but if you tried to refer to Singleton::s inside of main, you'd get an error as expected.

chwarr
  • 6,777
  • 1
  • 30
  • 57
  • so that means i can initialize static private object in global space ?? – govind parihar Nov 12 '13 at 10:38
  • 1
    @govindparihar, It isn't really that you are "[initializing a] static private object in global space". The `Singleton Singleton::s(47);` line is defining the variable `Singleton::s`. That is, it is saying where `Singleton::s` is stored and initializing it. This becomes important when there are multiple compilation units that need to be linked together. Only one of them can define `Singleton::s`. You may want to read [What is the difference between a definition and a declaration?](http://stackoverflow.com/questions/1410563/what-is-the-difference-between-a-definition-and-a-declaration) as well. – chwarr Nov 13 '13 at 08:45