Reputation: 34175
I want to provide static helper functions to handle the data type of a class. I considered including them in the class itself. Would they be instantiated for every new class instance or just once?
Upvotes: 3
Views: 662
Reputation: 126412
Functions are not "instantiated" (unless they are function templates).
Classes are instantiated, and instances of classes are objects. Each object takes space in memory, but functions are just procedures, pieces of code generated once and for all by the compiler, and space for them in memory is not allocated every time a new object is instantiated.
Functions can implicitly work on an instance of a class (if the function is a member function), but that's done just by passing a implicit pointer to the object they work on. Even in the case of member functions, therefore, be them static
or non-static
, there's no proliferation of pieces of code1.
If you meant to ask whether only one piece of code is produced for static
functions, rather than several separate pieces of code, then the answer is "Yes"; but then again the answer is the same for member functions.
1 Actually, virtual
member functions do require storing an additional pointer for every instance of a class that has at least one member virtual
function (this pointer would point to the so-called vtable). However, static
functions cannot be virtual
, so this does not apply to the case you are considering in the question.
Upvotes: 6
Reputation: 500227
No, there is no per-instance overhead associated with static
member functions.
Furthermore, there is no per-instance overhead associated with any member functions, with one exception. The exception is adding a virtual function to a class that didn't have any; typically, this would add an extra pointer to every instance of the class. Adding more virtual functions would incur no further per-instance overhead.
Upvotes: 4
Reputation: 8027
Member functions (static or otherwise) are only ever instantiated once. They never add any overhead to the class under any circumstances.
Upvotes: 1