You can execute a private function of B
using a pointer to that function; the complication consists of obtaining the pointer in itself since when pointing to a private data you can not access either. For that you can make a single friendly function whose definition is not accessible more than from A
:
A.hpp
#include "B.hpp"
struct A {
void f(); // Función que accede a una función privada de B
private:
B objeto_b;
};
B.hpp
struct B {
using Bfp = void (B::*)(); // Atajo al tipo de función void() de B
private:
friend Bfp dame_acceso(); // Función amiga
void f(); // Función privada de B
};
The object B
has a single function as a friend, so no type of access is granted to A
; function dame_acceso
returns a function pointer void B::()
but has no definition. We will hide the definition of dame_acceso
in the code file of A
:
A.cpp
#include "A.hpp"
// Esta definición sólo es visible aquí
B::Bfp dame_acceso() {
return &B::f;
}
void A::f() {
// Llamamos la función privada de B a través del puntero a función
(objeto_b.*dame_acceso())();
}
Since the definition of dame_acceso
is in the code file of A
, the definition will not be visible to other classes and other classes will not be able to obtain the private function pointer of B
. If you try to define another dame_acceso
in another translation unit, the program will fail to link.
You can see this example working in Wandbox 三 へ (へ ਊ) へ ハ ッ ハ ッ .
Another idea.
The pointer to member function is extremely complicated, you can achieve the same with less code by passing a reference to B
to dame_acceso
:
A.hpp
#include "B.hpp"
struct A {
void f(); // Función que acceder a una función privada de B
private:
B objeto_b;
};
B.hpp
struct B {
private:
friend void dame_acceso(B &); // Función amiga
void f(); // Función privada de B
};
A.cpp
#include "A.hpp"
// Esta definición sólo es visible aquí
void dame_acceso(B &b) {
b.f();
}
void A::f() {
// Llamamos la función privada de B a través del puntero a función
dame_acceso(objeto_b);
}