Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static class member of class's own type [duplicate]

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."

  • C++ Primer (Lippman Lajoie)

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 ?

like image 974
Amit Tomar Avatar asked Mar 28 '12 06:03

Amit Tomar


People also ask

How many copies of static members are there per class?

Only one copy of a static member exists, regardless of how many instances of the class are created.

How many copies are kept in memory for a static class?

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.

Can a static member of a class be private?

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.

What is a static member of a class?

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.


2 Answers

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.

like image 134
RolandXu Avatar answered Sep 28 '22 21:09

RolandXu


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.)

like image 30
James Kanze Avatar answered Sep 28 '22 21:09

James Kanze