Reputation: 79
I solved a problem using function pointers and I am a little concerned with the solution and need advice.
I am having several classes in my project which implements a memory table, a local data structure which keeps some data in the memory.
All the functions are private so that no body other than the class itself can use/modify the data using it's own functions.
Recently I had a requirement where I had to use this data in a different module. As I did not want to make private functions as public so I stored the function pointer (of the required functions) of all the classes in a std:map at the app start. Later I simply called the function by these pointers wherever I needed to modify the data of that specific class.
I want to know if this correct? Calling a private function of a class inside a different class using the function pointer?
Below is the code which somewhat simulates what I tried to implement:
typedef struct
{
void (*pfnDisplay)(void);
}FuncInfo;
std::map<int,FuncInfo> sFuncInfoMap;
//Stores the function pointer in a map
void RegisterFunction(void (*pfnDisplay)(void))
{
FuncInfo sFuncInfo;
sFuncInfo.pfnDisplay = pfnDisplay;
sFuncInfoMap.insert ( std::pair<int, FuncInfo>(1, sFuncInfo) );
}
class A
{
private:
static void Display(void)
{
printf("No one can access me");
}
public:
A()
{
RegisterFunction(Display);
}
};
class B
{
public:
void CallADisplay()
{
sStFuncInfoMap[1].pfnDisplay();
}
};
#pragma argsused
int _tmain(int argc, _TCHAR* argv[])
{
A a; //calls the constructor
B b;
b.CallADisplay();
return 0;
}
**Output:**
No one can access me
Thank you.
Upvotes: 0
Views: 487
Reputation: 254431
Yes, you can call a private function via a function pointer and, more generally, access any member indirectly via a pointer; although you can only create that pointer in a context where access is allowed.
Access control only prevents use of a member's name, not (indirect) access to the member itself.
Upvotes: 5