codeLover
codeLover

Reputation: 3810

C++: Static member function returning an object of self static for a class with private constructor

I've a C++ snippet as below. The "getInstance()" function is trying to return a static object of the same class "CAbc". This class has a private constructor so that objects of this class can't be created.

While calling this function in main(), like in below snippet, the returned object is not being collected anywhere in main() using any reference.

I'm trying to understand the below 2 points:

This is being called in the main() function.

class CAbc
{
private:
CAbc() {} // HAS A PRIVATE CONSTRUCTOR
.....
public:
static CAbc& getInstance()
    {
        static CAbc _self;
            return _self;
    }
    // what does this returning a static self object mean in C++ ?
}

main()
{
CAbc::getInstance();
// not collectig this anywhere ?
}

Upvotes: 1

Views: 4882

Answers (1)

Manuel
Manuel

Reputation: 2554

As @tkausi says, the static member function can create an object, as it is a member (thus having access to private methods.)

What this code does is having an instance of the class, only one object (_self) and returning it for use.

Why nobody gets the return value? Because the call is there only to create the instance. If you don't call the function no _self object will be created.

class CAbc
{
private:
    CAbc() { cout << "creating" << endl; }
public:
static CAbc& getInstance()
    {
        static CAbc _self;
            return _self;
    }
};

int main() {
    cout << "Begin" << endl;

    //CAbc::getInstance();
}

With the call to getInstance commented out you won't see the "creating" output.

If you uncomment the call, you'll see:

Begin
creating

Once created, the function will always return the same object.

Upvotes: 1

Related Questions