As I understand, each instance of a class has its own member variables in memory, so that it can store different values for different objects. However, it is not the same for member functions. Member functions are reused across objects of a class, so it only has one address with one block of memory to refer when needed by all objects.
Static function is made to access static members. However, static function also exists only one during the lifetime of its application. Aside from being the static accessor, at low level it is not different with normal class functions, isn't it? Or maybe I'm wrong, that each class has its own functions?
Non-static functions accept additional parameter, this, which is the pointer to the class instance with the instance-specific variables.
Static functions don't have this parameter (thus you can't use this in a static function and can only access static data members).
This differs from language to language, but in C or C++03 functions generally map on assembly functions; that is they exist once in memory (whether free functions, class functions or class static functions) and take arguments as parameters, including a this pointer for member functions that is implicit.
In C++11, lambda functions introduce a novelty: each instance of the so-called function will carry some state. From an implementation point of view, it therefore means that a "regular" function needs be created and it is associated to an anonymous bundle of data (if necessary). The function need not be duplicated each time the lambda is created, but the data does. One helpful figure is to remember that lambdas (in C++) replace function objects (or predicate objects): they are just syntactic sugar, the implementation is similar.
The only difference between static and member functions is that member functions always have the this pointer passed in automatically.
simply if it is referred, static functions creates a single set of memory for itself and are meant for static data-members which are generally not changeable. But non-static functions creates separate set of memories for each instances and are meant for both non-static and static data-members. If u require stable output go for static and if u require the alternate go for the non-static.
Related
In C++ implementations, typically code is not stored (in any form) inside class instances. The code segment is not in the same memory space as objects and the like. This means that member functions are not "stored" inside class instances.
But when a question was asked about this, I got to wondering: to what extent, if at all, does the standard prohibit member functions being stored inside their encapsulating class, to the extent that instantiating the class makes a copy of those functions? Theoretically, could I make an implementation that worked this way? And could it even remotely abide by the common ABIs?
If, in C++, code were a first-class value, then the code for a member function would be simply a const static class member, and you would no more expect to find that in an instance than you would any other static data member. (§ 9.4.2: "A static data member is not part of the subobjects of a class.")
However, code is not considered a value, and furthermore you cannot even construct a pointer to a member function (although you can construct a "pointer to member", that is not really a pointer since it is not usable without a reference to an instance). That makes member function code different both from static data members and non-member functions, both of which allow the creation of free-standing pointers, which furthermore have equality guarantees which (more or less) preclude copying.
Class instances do contain a reference to virtual member functions (indirectly, in most implementations; the pointer is actually to a static vtable) which must be copied when a new instance is created. No requirement is made on the size of the reference, so in theory (as far as I know) there is nothing to stop an implementation from avoiding the indirections and storing the entire code anew for each instance of the class.
But there is an exception for standard-layout types, which is a subset of classes with no virtual member functions, expressed in § 9.12/18, which requires that two standard-layout types with identical initial members have identical layout for the initial members. Recalling that standard-layout objects must be simply copyable with memcpy (§3.9/3), must be contiguous in memory (§1.8/5), and must include their members in order (§9.12/13), this requirement makes it effectively impossible to include class-specific static data in any standard-layout object, which would include the code for member functions.
So I conclude that at least for standard-layout objects, the C++ standard does prohibit the storage of static data, including code for member functions, within the object representation.
If each member function is only contained once per class (to be shared by all instances) what exactly is the purpose of declaring a member function static? Is it like a function being declared const, in that it modifies a particular type of data (in this case, static data members)?
Normal member functions require a class instance to run. Static methods can be called directly without first creating an instance of the class.
Normal method:
MyClass myClass;
myClass.NormalMethod();
Static method:
MyClass::StaticMethod();
So normal methods are perfect for functions that work with the class data. If a method doesn't need to work with the class data, then it would be a candidate for possibly being made static.
Class methods, static or otherwise, can access private members of any of that class's objects, not just its own instance. Same goes for static methods, which don't have an instance unless you pass one to them.
You could also use a free function and declare it a friend, but a free function implies a higher level of abstraction that may operate on objects of different classes. A static class method says "I only make sense in light of my class"
One application of static methods is to create instances and return pointers. For example, there may be derived classes that the caller isn't supposed to know about - the "factory" function knows which derived class to use.
Of course when you need to create an object, you probably don't already have an object to use for that, and even if you do that other object isn't relevant.
Basically, sometimes some action is an aspect of the abstraction that a class provides, but that action isn't associated with a specific object - or at least not one that already exists. In that case, you should implement the action as a static function.
Similarly, some data is related to the abstraction provided by a class but not to a particular instance of that class. That data is probably best implemented as static member variables.
I need to mock a free function interface in my unit tests. For this reason, I include the mocked function as a static member in a class. I can the save the state of this mock in static class members. I've included the function free in this class to free the memory associated with the static members, which gets called at the end of each test case. This function is effectively a destructor. What would be a good name for the constructor equivalent of this function? That is, the function that is called on construction of the test fixture for each test case?
If the function only allocates data structures without initialising them, allocate or a variation thereof would seem appropriate (this is also the name used by the C++ STL Allocators).
If the function only initializes data structures allocated elsewhere (for example on the stack or as direct members of another object), initialize or a variation thereof would seem appropriate.
If the function does both allocation and initialization, create is a common name (prefix) used in C for such functions.
What is the Design and Performance impact for making all functions static which do not touch the member variable of the class?
You should actually consider making them non-static free functions, as explained in detail in this question. This question is also very interesting.
In a nutshell, these question explain that you should prefer non-friend non-member functions whenever possible (meaning when they do not access non-public members).
What are Design and Performance impact for making all function static which do not touch member variable of class?
performance: static member functions may be slightly faster than non-static member functions because they don't need to pass a this pointer, but you're unlikely to notice the difference; where inlining is used there may not be one. Further, pointers to a static function may be used directly, whereas "pointers" to non-static member functions are typically offsets/indices and require a this pointer for use; the run-time CPU operations involved can be expected to be slightly more complicated.
design: the choice between static and non-static member function can safely be made on the basis of the need to access an object's non-static member data in order to fully perform the expected operation. If you're generally comfortable with OOP and it doesn't seem intuitive and sensible to call the function using the notation object.fn(x, y, z) - that the function lends itself to being perceived as an operation on the current state of that specific object - then it probably shouldn't be a non-static member.
Ignoring the question as I understand it and looking at the wider terrain, free functions do have their own advantages as discussed in other replies; countering that the tighter association of static members can help programmers find potentially useful routines - all depending on the tools and habits they have.
Performance-wise, static member functions are faster and use less stack space because they do not need to pass a this pointer. But this isn't a significant cost.
Regarding design, you should ask yourself why the functions are members of the class if they do not access its data members? There certainly are design patterns that include static functions. However, a widely favored approach to class design is to choose the minimum number of functions necessary to expose the functionality of the class while keeping its data hidden. This makes it easier to change the internals of the class without knock-on changes to the code which uses the class. Such an approach has little use for static functions as they cannot provide access to the data.
Absolutely yes. The non-static member functions are meant to cater the non-static member variables. If variables are not used then the function should be made static which makes your design cleaner and you can avoid passing this as the 1st hidden argument (which betters the performance a little).
[Note: On funny side there is one notable exception:
struct A {
virtual void foo (int) = 0;
};
Even though you don't have member used inside foo() you can't make it static ! :)]
Sometimes it makes sense to make a function virtual even if it does not access any instance members - for example to return some class-related properties (something like virtual bool eatsPlants() in the animal class hierarchy). Then it cannot be static because there are no virtual static members in C++.
Performance of static member functions vs free functions?
There is absolutely no performance difference between static member functions and free functions.
Performance of static member functions vs non static member functions?
Typically static member function are used to eliminate the need for an object and eliminate the extraneous this argument and that is the only performance advantage over non static member functions but it is hardly noticeable.
It depends. First, of course, if the function is to be virtual, then it
can't be static. (Most of the member functions I have which don't touch
a member variable are virtual. Otherwise, why make it a member at all?)
Otherwise, it depends on the role of the function in the class. If it
is fundamentally independent of any instance of the class (e.g. it sets
some global parameter of the class, which affects all instances), then
it should be static; such functions should be fairly rare, however. If
on the other hand, it only incidental that it doesn't touch a member
variable;, if conceptually, it does involve the specific instance, then
make it a member. (This is frequent in the case of virtual functions,
but probably very rare otherwise.)
If you have data for a class that will be modified and needs to be retained throughout the program, but is only used in one member function, is it preferred to make that variable a local static variable of the routine that it is in or make it a member of the class?
The question isn't "will the data be used throughout the program", but rather "if you make two objects of this class, do you want them to share this data?" If yes, make it static. If no, don't.
I would argue that in most cases, you should never use a local static variable, and instead use a static member variable. Then the question degenerates to if that variable should be shared among the class instances or not.
Declaring a local variable as static means your method now has state, separate from the object's state. It can lead to many mistakes when maintaining this code (such as copy constructor implementation, assignment, serialization) and when reading it (unclear method behavior).
Avoid using static locals unless you have some good reason (the only one I can think of is single threaded singletone implementation).