I have a class that I'm refactoring it and would like to add a helper function to eliminate some code duplication in both static and non-static methods, so the helper function must be static. When I go to call the helper function from inside the non-static method, will I need to use the double colon notation, MyClass::helper_function(x, y, z), the arrow notation, this->helper_function(x, y, z), or just helper_function(x, y, z)? If the helper function was public would you be able to access it from an instance with the dot notation, myObject.helper_function(x, y, z)? I'll try it out in a couple of minutes, and I'm sure I'll figure it out, but I thought it was a good gedankenexperiment to try to figure out what will happen.
Should I just make the helper function not a member of the class at all, but just put it in the class's .cpp file to make it accessible to the class's methods? What is the best practice?
All three formats work.
MyClass::helper_function - this is a Qualified Name. The class name is looked up first, finds the current class, and then the static method is found in the class.
helper_function - this is an unqualified name. it will be looked up in the class scope first, before the surrounding scope would be tried. But since helper_function is a static method in the class, no further searches are done
this->helper_function - This is the most unusual of all. The this pointer has type MyClass*, so the search is restricted to MyClass. But once helper_function is found, it turns out that the this pointer isn't actually needed. That doesn't invalidate the name lookup.
Class member or not?
A static helper function may access other class members, in particular private members. This includes private constructors, private destructors, private nested types, constants, etc. If you need one of them, a static method is the only reasonable choice.
Yes, you can access static methods by way of the this pointer and the . or -> notation.
Related
When should I mark the static method of a specific class as private other than public?
What aspects should I consider when making such considerations.
What are the advantages for mark the static method as private?
Any simple example would be appreciated, which could help me fully understand this matter.
UPDATE:
As per this answer, which says that[emphasise mine]:
This function could easily have been made freestanding, since it doesn't require an object of the class to operate within. Making a function a static member of a class rather than a free function gives two advantages:
It gives the function access to private and protected members of any object of the class, if the object is static or is passed to the function;
It associates the function with the class in a similar way to a namespace.
How to fully understand the statements above?
The general rule for methods (static or otherwise) is to make them private if possible — i.e. unless you absolutely need them to be callable from other classes (which is to say, you need them to be part of your class’s public API)
The reason for making as much as possible private is simple: in the future, you’ll be able to change anything that is private, without breaking a bunch of other classes that were written to call the old version of the method. Changing a public method is more problematic, because other classes might be depending on it.
Can anyone explain why we can call static member functions without creating instance of an object but we can't in case of non-static functions?
I searched everywhere, I couldn't find an explanation, Can you help?
You've got the logic basically in reverse. It is useful to have functions that belong to a class, even though they do not need to be called on an object of that class. Stroustrup didn't want to add a new keyword for that, so he repurposed the existing keyword static to distinguish such methods from normal methods.
In hindsight, other options could have been chosen. We could have made this an explicit function argument for the normal methods, for instance. But that's about 30 years too late now.
Why?
Because we like encapsulation and modularity which we get when using object orientated patterns.
You can view static class member functions and variables as a way of encapsulating what would otherwise have been global functions and variables - which might collide.
Underneath, there is not a great deal of difference between a plain old C++ file with some functions declared and implemented in it, to a class filled with only static functions. The difference is we can cleanly access a set of functions attached to a parent class.
An example:
Suppose you want to create a new class like MyMediumInteger, and you want developers to determine what the maximum number it can hold is. This information is applicable for every instance of MyMediumInteger, no matter what the state of the private member variables are. Therefore it makes sense to expose this information without forcing the developer to instantiate the class. Your options include defining something global such as #define MYMEDIUMINTEGER_MAX ... which could collide with a define sharing the same name in another module, or create a static function returning the max size, called neatly via
MyMediumInteger::maxSize().
A code example:
/***
* Use a static class member function (or variable)
*/
class MyMediumInteger
{
public:
static unsigned long maxSize() { return pow(2, 32) - 1; };
};
auto maxSize = MyMediumInteger::maxSize();
/**
* Alternative approaches.
* Note: These could all collide with other #defines or symbols declared/implemented in other modules.
* Note: These are both independant sources of information related to a class - wouldn't it be nicer if they could just belong to the class instead?
*/
/***
* Use a #define
*/
#define MYMEDIUMINTEGER_MAX (pow(2, 32) - 1)
auto maxSize = MYMEDIUMINTEGER_MAX;
/**
* Use a global function or variable
*/
static unsigned long getMyMediumIntegerMaxSize()
{
return pow(2, 32) - 1;
}
auto maxSize = getMyMediumIntegerMaxSize();
A word of warning:
Static member variables and functions have some of the pitfalls of global variables - because they persist through instances of classes, calling and assigning to them can cause unexpected side effects (because static member variables get changed for everyone, not just you).
A common pitfall is to add lots of static member functions and variables for management - for example, maintaining a list of all other class instances statically which gets appended to in the constructor of each class. Often this type of code could be refactored into a parent class whose job it is just to manage instances of the child class. The latter approach is far more testable and keeps things modular - for example, someone else could come along and write a different implementation of the management code without appending to or re-writing your child class implementation.
How?
In C++ class member functions are not actually stored in class instances, they are stored separately and called on instances of classes. Therefore, it's not hard to imagine how static functions fit into this - they are declared in the same way as normal class member functions, just with the static keyword to say "I don't need to be given a class instance to be run on". The consequence of this is it can't access class member variables or methods.
Static member functions does not need a "this" pointer, it belongs to the class.
Non-static functions need a "this" pointer to point out in which object it belong to, so you need to creat a object firstly.
Because that's what static means: "I don't want this function to require an object to work on".
That's the feature. That's its definition.
Any other answer would be circular.
Why is it useful? Sometimes we want to be able to "organise" some data or utilities in our classes, perhaps for use by external code or perhaps for use by non-static functions of the same class. In that sense there is some crossover with namespaces.
I am using SDL2_mixer library, but I believe that the question should hold for the general case also.
Currently, a function that I would like to use, Mix_HookMusicFinished(void (*music_finished)(void)) has a set callback to the global scope for a C style function. However, I would like to have that callback be set to a member function within my own class void CMusic::musicFinished() without having the need for a function in global scope.
Is there anyway to do this? Something like Mix_HookMusicFinished(musicFinished) would be great, but that directly has an error of argument of type "void (CMusic::*)()" is incompatible with parameter of type "void (*)()"
You need to make a "wrapper" function. However, the problem here is that you also need to be able to find the CMusic object that you want to "finish" - this is really what the crux of
argument of type ... is incompatible with ...
is all about. Since there is no way to pass a parameter to the musicFinished object, you will need some other way of "finding" the CMusic object.
If we assume there is a way to do that, then something like this would work:
class CMusic
{
...
public:
...
static void musicFinishedWrapper();
void musicFinished();
...
};
void CMusic::musicFinishedWrapper()
{
CMusic* music = getTheMusicSomehow(); // No idea how you do this - depends on your code.
music->musicFinished();
}
The reason you have to have a CMusic object is that your musicFinished expects a (hidden) this pointer argument - which is the value in music in my little function.
You could move musicFinished to your CMusic class and declare it as a static class method. static class methods aren't called on an object; they therefore don't have an implicit argument to specify the value of the this pointer, and they therefore can have the same signature as freestanding functions. You additionally can make it private to prevent anything but CMusic from using it.
However, since your musicFinished method currently works as a freestanding function and therefore probably doesn't need access to CMusic's protected or private members, and since your efforts to limit its scope presumably means that you don't want other things to call it, I personally would leave your musicFinished function as freestanding but declare it as static (or move it to an anonymous namespace, if you prefer) within the CMusic source (.cpp or .cc) file. Doing so would restrict its scope to the source file (the "compilation unit"). An advantage over a private, static class method is that it does not need to be exposed at all in a header file, so it is in some sense more private.
In C++, I have a static member variable in a class.
Then I pass this static member variable to a array of struct initialization. Now my problem is the value of that member in struct is gone.
Please explain if I'm missing some understanding about a static member variable. Did a static member have a limitation of passing its own value?
Please advice.
Many thanks
A static member variable is like a regular global except that:
Its name is scoped to that of the class in which it is a member. The class acts like a namespace, but in a more powerful way as it can be used in templates.
It can be protected or private in which case only those that have access to the class can access the member.
There is one instance of this, not one per object.
Private static member variables can usually be replaced with a "hidden" variable of the same type in the anonymous names of the compilation unit for the class. This is a preferable option as you then do not need to expose the implementation of your class (which is what private members usually are) in the header.
It would be useful to give an example that duplicates your error so we can see exactly what you are trying to do and why it does not work.
I have a class with two member functions that share a piece of code:
void A::First()
{
firstFunctionEpilogue();
sharedPart();
}
void A::Second()
{
secondFunctionEpilogue();
sharedPart();
}
Currently firstFunctionEpilogue(), secondFunctionEpilogue() and sharedPart() are not function calls but just pieces of code, sharedPart() code being duplicated. I want to get rid of the duplication.
The shared piece of code doesn't need access to any members of the class. So I can implement it as any of the three:
a static member function,
a const non-static member function or
a local function.
Which variant is better and why?
If your function accesses state but does not change it then use a const member function.
Your case:
If it your function 1) doesn't need access to any member of the code, and 2) is related to that class, then make it a static function of your class.
That way it is clear that it is not modifying state, nor based on the state of the object.
An extra case you didn't mention:
There is another thing you can do too. And that is to make your SharedPart take in a member function pointer and to call it and then process it's main body. If you have a lot of First(), Second(), Third(), Fourth(), ... such functions then this can lead to less code duplication. That way you don't need to keep calling SharedPart(); at the end of each member function, and you can re-use First(), Second(), THird(), ... without calling the SharedPart() of the code.
I'd say:
It probably doesn't matter, so it's not so much "best practice" as "just don't do anything crazy".
If the class and all its members are defined in its header, then a private static member function is probably best, since it clearly indicates "not for clients". But there are ways to do this for a non-member function: don't document it, put in a comment "not for clients", and stick the whole thing in namespace beware_of_the_leopard.
If the class member functions are defined in a .cpp file, then little helper functions like this are best as free functions in the .cpp file. Either static, or in an anonymous namespace.
Or it could be in a different class.
Or, if it's a member, it could be virtual.
There are a lot of decisions, and I wouldn't stress out about it too much. Generally, I opt for a const non-static member function as a default unless I have a good reason not to do it that way.
Prefer static if clients need to call it without having an instance
Prefer local functions if you don't want to clutter the .h file or you want it completely hidden in the .c
Make it a non-member function
The shared piece of code doesn't need access to any members of the class.
As a general rule, if a piece of code doesn't need access to any members of the class don't make it a member function! Try to encapsulate your classes as much as possible.
I'd suggest doing a non-member function in a separate namespace that would call the public methods and then call the function you made for the shared code.
Here is an example of what I mean :
namepsace Astuff{
class A{...};
void sharedPart(){...};
void first(const A& a);
void second(const A& a);
}
void Astuff::first(const A& a){
a.first();
sharedPart();
}
a static member function, a const
non-static member function or a local
function.
Generally, it should be a member function of another class, or at least non-static member of the class itself.
If this function is only called from instance members of a class - probably its logical meaning requires an instance, even if syntax does not. Can anything except this object provide meaningful parameters or make use of the result?
Unless it makes sense to call this function from outside of the object instance, it shouldn't be static. Unless it makes sense to call this function without accessing your class at all, it shouldn't be local.
Borrowing examples from Brian's comment:
if this function changes global state, it should be member of a class of global state;
if this function writes to file, it should be member of a class of file format;
if it's refreshing screen, it should be member of... etc
Even if it's a plain arithmetic expression, it may be useful to make it a member (static or not) of some ArithmeticsForSpecificPurpose class.
Make it a non-member non-friend function. Scott Meyer's has a great explanation for this here (and also Item 23 of Effective C++ 3rd Edition).
As a rule of thumb "try to keep it as local as possible but as visible as necessary".
If all code calling the function resides in the same implementation file, this means keeping it local to the implementation file.
If you'd make it a private static method of your class, it would not be callable by implementaions including your class, but it would still be visible to them. So every time you change the semantics of that method, all implementaions including your calls will have to recompile - which is quite a burden, since from their point of view, they don't even need to know those sementics.
Thus, in order to minimize unnecessary dependencies, you would want to make it a static global function.
However, if you should ever find yourself repeating this global function in mulitple implementation files, it would be time to move the function into a seperate header/implementaion file pair, so that all callers can include it.
Whether you place that function into a namespace, at global scope, or as a static function in a class is really up to taste.
On a final note, if you go for the global static function, there's a "more c++ like" version: anonymous namespaces. It has the nice property that it can actually store state and also prevents users for being able to even forward declare any of its functions.
// in your .cpp file
namespace /*anonymous*/
{
void foo()
{
// your code here
}
};
void MyClass::FooUser1() { foo(); }
void MyClass::FooUser2() { foo(); }