govind parihar
govind parihar

Reputation: 21

private static object accessed in global space

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;
}

Upvotes: 0

Views: 131

Answers (2)

chwarr
chwarr

Reputation: 7202

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.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409384

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.

Upvotes: 1

Related Questions