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 static method can be called directly from the class, without having to create an instance of the class.
A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::. A static member function can only access static data member, other static member functions and any other functions from outside the class.
A static member has certain special characteristics. These are: Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created.
Because static member functions are not attached to a particular object, they can be called directly by using the class name and the scope resolution operator. Like static member variables, they can also be called through objects of the class type, though this is not recommended.
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)
{}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With