Possible Duplicate:
Do static members of a class occupy memory if no object of that class is created?
Memory Allocation of Static Members in a Class
"A class is not considered defined untill its class body is complete, a class can not have data members of its own type. A class can have data members that are pointers/reference to its own type."
Makes sense.
But why is this allowed then ?
class justAClass
{
public :
justAClass();
private :
static justAClass justAMember;
}
For pointers it is understandable. But how will this above thing work ? How will i ever decide the size for object of such a class ? Isnt it a recursive case (with no base condition) to have a member of its own type, even if it is static ?
Only one copy of a static member exists, regardless of how many instances of the class are created.
No multiple copies of static is maintained. all objects have same static variables. If they have it then you have to access them using object but this is not what we do with static . The Penalty of storing references = penalty of creating the class.
If it is private, use a static member function to read or write it. A static member function: • Is like an ordinary non-member function, but its scope is the class. It can access all members of an object in its class, but only if you make the object available, such as in a parameter - there is no "this" object.
Static members are data members (variables) or methods that belong to a static or a non static class itself, rather than to objects of the class. Static members always remain the same, regardless of where and how they are used.
The reason for class can't have data members of its own type is the compiler must know the size of class object. For example, one class is a local variable in function, the compiler can handle the stack only it knows the class size.
For your case, the static class member doesn't reside in class object, so has no impact to size of class object. It's OK.
Formally, the distinction is that the declaration of a static member in a class is not a definition. You must provide a definition elsewhere (exactly once), and the compiler doesn't need to know the size until it encounters the definition. Static members do not impact on the size of the class itself. (In many ways, the static member declaration in the class is very much like an extern
non-member declaration.)
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