I want to update some C legacy code to C++. Suppose I had something similar to this code in C:
//my_struct.h
typedef struct myStruct {
//some members go here
} myStruct;
int f1(myStruct*);
void f2(myStruct*);
//my_struct.c
#include "my_struct.h"
static int helper(myStruct* st)
{
return 21;
}
int f1(myStruct* st)
{
return helper(st);
}
void f2(myStruct* st) {}
If I update it to the following in CPP:
//myStruct.h
struct myStruct {
int f1();
void f2();
private:
int helper();
};
//myStruct.cpp
int myStruct::f1(){
return helper();
}
void myStruct::f2(){}
int myStruct::helper(){
return 21;
}
What is the impact of converting the global static C function to a private member function in C++?
What would be the pros/cons (regarding compilation, linking, runtime) between the previous approach and the following one? I didn't use the parameter inside the function to make the example short (If it is not used I read in other questions that it should probably go to the anonymous namespace).
//myStruct.h
struct myStruct {
int f1();
void f2();
}
//myStruct.cpp
namespace{
int helper(myStruct *st){
return 21;
}
}
int myStruct::f1(){
return helper(this);
}
void myStruct::f2(){}
The impact is that you've made a (private, internal) implementation detail of your module part of the (public) interface.
Cons:
you've added semantic noise to your interface
ie, there's more for clients to read and think about, even though it shouldn't affect them,
changes to internal implementation details may require all clients of the interface to recompile, instead of just re-linking
ie, if you want to change
helper
, that now updates the public header and causes widespread recompilation of files that shouldn't be affectedPros:
It's idiomatic in C++ to add implementation-file-local details like
helper
to the anonymous namespace.