Static member object of a class in the same class
c++, constructor, static
Solution
But how could we declare static object of the same class in the class.
A `static` member variable is not stored inside each object of a class. So if you declare a `static` member variable inside a class or as a namespace level object after you defined the class, differs only in respect to access (`Class::var` and `var`) and access to `protected` and `private` members.
And also one thing more since `e` is a static object, and static objects can call only static member functions
I think you are mixing `static` functions and `static` objects. Inside a `static` function you can call only `static` functions (unless you are calling them on an object).
so how could the constructor been called here for static object `e`
Like for every other object a constructor has to be called for `static` objects, too.
also its constructors are private
Access Control is checked on class level in C++. So since the `static` object is inside the class, it can access `private` members.
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 (`other` in this case):
class Test {
private:
int i;
public:
Test(const Test &other)
: i(other.i)
{}
};
Problem
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.