Suppose we have a class as
class Egg
{
static Egg e;
int i;
Egg(int ii):i(ii) {}
Egg(const Egg &); //Prevents copy-constructor to be called
public:
static Egg* instance() {return &e}
};
Egg Egg::e(47);
This code guarantees that we cannot create any object, but could use only the static object. But how could we declare static object of the same class in the class.
And also one thing more since e is a static object, and static objects can call only static member functions, so how could the constructor been called here for static object e, also its constructors are private.
A
staticmember variable is not stored inside each object of a class. So if you declare astaticmember variable inside a class or as a namespace level object after you defined the class, differs only in respect to access (Class::varandvar) and access toprotectedandprivatemembers.I think you are mixing
staticfunctions andstaticobjects. Inside astaticfunction you can call onlystaticfunctions (unless you are calling them on an object).Like for every other object a constructor has to be called for
staticobjects, too.Access Control is checked on class level in C++. So since the
staticobject is inside the class, it can accessprivatemembers.Unlike in some other languages, the following is legal in C++, since the access to a private member is from inside the class – even if on another object (
otherin this case):