Can a existing static method made global using function pointer? - c++

I have a static method in a cpp file (not in class) .
I want to use it globally without redeclaring it as extern .
In that case is it possible to use a global function pointer to this static method and
use this function pointer globally ??

It is possible to do what you want, but why would you avoid using extern when it does exactly what you are trying to emulate through a much more convoluted (and unreadable) mechanism?

The static declaration in C tells the compiler not to to add the function the symbol table. This means that the inker has no way to link that function in if needed by other modules. The function will still exists (but is invisible to the linker) so if one records the address of the function in a pointer one will be able to call the function with no problem.
So short answer is yes, it is ok.

Yes, making a public pointer while hiding the implementation is generally what you might expect in a factory style pattern.
It might be interesting to know why you say "I want to use it globally without redeclaring it as extern ."
Why is changing the declaration from static (making it available in that module only) to extern (making it available outside the module and publishing it) an action you want to avoid?

If it is static in a cpp file in the global namespace, then the function can only be used directly from within that cpp file. It is a kind of private helper function.
What you can do is to make a typedef on the function's prototype and introduce a public function that returns a pointer to the function or a table of pointers to different functions, which is often done in order to implement plug-ins and have some callbacks or api methods registered. + point is that you do not have a strong binding to the function.

the static specifier implies internal linkage.
You want static with external linkage, which does not require an explicit storage specifier. If your function is at namespace scope, simply remove the 'static' specifier. The default behavior at namespace scope is static with external linkage.

Related

Private C++ member function vs C function

I have a C++ class, and in one of the member functions there is a duplicate section of code. So I've extracted this out into a function, however only this member function will call this new function. At the moment it's just a c function defined in the cpp file and not declared anyway else.
Is there any advantage to making this a private C++ member function, the code in the function itself doesn't use any instead variables of the class.
Well, if it's any addition to the argument, the newest CppCoreGuidelines say that you should "C.5: Place helper functions in the same namespace as the class they support". So they shouldn't be a part of the actual class, but part of the namespace that they reside in.
If you add it to the class then it becomes part of the classes signature.
As such making changes to the function signature would change the class signature. Given it would be a private function it is not likely that you would gain much by exposing it in that way.
If though it needs to access internals of the class then having as part of the class would likely simplify its implementation.
If it does not need to access the internals you can make add it to an anonymous namespace within the cpp file. That way the function symbol will not be exposed anywhere that is is not needed.
(Sort of an extended comment)
You've declared a free function in the .cpp file.
This a good design decision as other answers point out. The clearest thing you can have is a method only visible from that .cpp file that can't see or change state. I might be tempted to put it in the same namespace as the class as per the CppCoreGuidelines.
Equivilently, you could have declared a private static member function in your header file. This is static in the C#/Java sense rather than in either of the C senses (C++ has all of these meanings). However, I don't see the benifit as the only thing you gain is unnecessary recompilations.
Yes. Putting the function in class defines scope and context of it. This makes maintenance easier and also will allow you to extend its functionality in the future without significant code rewriting. Actually, in such cases I usually prefer making the function static in the class, i.e., meeting somewhere in the middle.

Static member vs static global

I have read that the difference between globals and static globals is that the global variable can be referred to in another implementation file via extern, whereas static globals are localized to only that implementation file. See these two questions for more information: [1, 2].
From what I understand, this means the that the following foo() and bar() should be linked identically. Both functions can only be used by MyClass.
//MyClass.h
Class MyClass{
private:
static void foo();
};
//MyClass.cpp
void MyClass::foo(){}
static void bar(){}
I can see foo()'s declaration being more common since it lets the header file lay out the entire class more completely (even if you can't/shouldn't use the private stuff), but is bad practice declare a function like bar() (hidden from the header file)?
For context, I am defining a WNDPROC for windows messages which needs to be static to work, but it's a rather ugly declaration and I'm not sure if I should hide it completely in the implementation file or go ahead and declare it in the header file.
static is a very horrible keyword as it has many different meanings depending on the context. static variables and static functions are completely different, and a static function in a class and a static free-function are completely different.
A static function in a class means that the function can be called without an instance of the class, but it cannot access non-static members of the class. It is a bit like a regular function, just enclosed in the class for tidiness purposes.
A static free-function has internal linkage, so it cannot be seen outside of the source file and its name can be reused in other source files.
A static class function does not have internal linkage. All class functions have external linkage. You can split the class function between header and source files whether the class function is static or not.
I recommend you read some tutorials/books to understand the many different uses of static more clearly. When you see static in a place you've not seen it before, assume nothing!
If you have a free-function which you want hide in a source file, you can declare it static as you have done so. Alternatively you can place it in an unnamed namespace.
// cpp file only
namespace
{
void hiddenfunc() {..}
}
This is similar to
static void hiddenfunc();
And it can be called in the same way (just as "hiddenfunc()"). An advantage of unnamed namespaces (a weird name, I know) is that you can also place classes and other definitions, that you only want to be visible within that source file. Just make sure you define the function body within the namespace {..} area. Don't put an unnamed namespace in a header file.

Is there any way to change the scope of a callback without changing the paramaters?

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.

global self created object

I am making a VC++ 2008 windows project, and I want to have an object that I instantiate exist for all intense, and purposes globally. this object shall be a timer to monitor how long the program has been running, and needs to be accessible by other objects for the purpose of log file generation. I know that I can mark native, and sudo-native (string) members as extern to make them reachable, but how do I get an object to exist globally to other objects.
Do I put the object definition before the class of the object that needs to know of its existence (insuring to load the class first), or must I put a method in my main that allows access to the object?
Just create a class with the methods you need, then declare an instance of the class global
include the header of the class in all your modules where you want to use it plus have
an extern declaration telling the modules that the definition is elsewhere. Maybe you
have some common header that all include.
extern MyClass yourInstance;
The global definition should be where the main() is
MyClass yourInstance;
or if you prefer allocate it on the heap by using a pointer, then allocate at start of main
and delete at end and just have the pointer as global.
that said, it is normally not good to have global declarations instead you should declare
the MyClass in the main() and then pass a pointer to it to all functions/classes that
you use. that is how i would do it. Then you don't need the extern statement and just
include the header MyClass.h
one problem with global instances is that you have little or no control of when they are
created/destroyed.
What you describe is often done using a singleton.
Here's an example on how to write one: Singleton: How should it be used
Here's another one:
Can any one provide me a sample of Singleton in c++?
Also note: What is so bad about singletons?

Which is best for a repeating piece of code?

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(); }