thexeno thexeno - 4 months ago 22
C++ Question

Why passing the reference of a private function to an external one is working?

I wonder if it is safe (and why) to pass the reference of a function which cannot be normally called.

In other words in the file myFunct.cpp I have something like this:

#include "externalStuff.h"
#include "myFunct.h" // myFunct_publicFunction proto

static void myFunct_foo(void);
static void myFunct_foo(void)

void myFunct_publicFunction()

Inside the externalStuff the reference is associated in this way:

externalStuffClass::init(void (*function)(void))
externalStuffReference = function;

This code snippet actually compiles and when the externalStuffObj somehow call the stored reference of the myFunct_foo it executes correctly.
I thought that declaring a static function inside a source file was the equivalent to have a private function in C, and so cannot be used by functions not contained in such source file.

My question is if this is safe, or it is working due to the lucky factor and can mess with pointers.


By declaring a function as static affects its linkage []. In this case, it has only internal linkage (see the second bullet here) meaning you the linker will be unable to see that function from another translation unit. However, it doesn't mean you cannot take the address of such function and pass it to another module.

It's almost a similar to leaking private members:

class MyClass{
    MyObject obj;
    MyObject* get(){ return &obj; }

There are many legal and valid reasons to do that; still, that opportunity can also be abused.