I was asked a very interesting question during a C interview: How can you implement a function f() in such a way that it can only be called from a particular g() function. If a function other than g() tries to call f() it would result in a compiler error.
At first, I though this could be done with function pointers and I could get close to blocking the call at runtime. But I was not able to think of a compile time strategy. I don't even know if this is possible using ansi C.
Does anyone have any idea?
Private Methods can only be used inside the class. To set private methods, use the private access specifier. Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members.
You can make module-private functions with the static keyword: static void func(void) { // ... } Then, func() can only be called by other functions defined in the same file (technically, the same translation unit: other functions whose definitions are included by a #include directive can still access it).
You should make a function private when you don't need other objects or classes to access the function, when you'll be invoking it from within the class. Stick to the principle of least privilege, only allow access to variables/functions that are absolutely necessary.
Here's one way:
int f_real_name(void) { ... } #define f f_real_name int g(void) { // call f() } #undef f // calling f() now won't work
Another way, if you can guarantee that f()
and g()
are the only functions in the file, is to declare f()
as static
.
EDIT: Another macro trick to cause compiler errors:
static int f(void) // static works for other files { ... } int g(void) { // call f() } #define f call function // f() certainly produces compiler errors here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With