Able to use pointer to function to call private method of an external class

Olumide picture Olumide · Dec 18, 2014 · Viewed 7.7k times · Source

Based on the following answer to a recent question, I'm able to use a function pointer in order to call the private method Foo<T>::foo() from another class Bar, as shown below (see also ideone)

#include <iostream>

template<typename T>
struct Bar
{
    typedef void (T::*F)();

    Bar( T& t_ , F f ) : t( t_ ) , func( f )
    {
    }

    void operator()()
    {
        (t.*func)();
    }

    F func;
    T& t;
};

template<typename T>
class Foo
{
private:
    void foo()
    {
        std::cout << "Foo<T>::foo()" << std::endl;
    }

public:    
    Foo() : bar( *this , &Foo::foo ) 
    {
        bar();
    }

    Bar<Foo<T> > bar;
};

int main()
{
    Foo<int> foo;
}

This works on MSVC 2013 and GCC 4.8.3. Is it valid?

Answer

sdzivanovich picture sdzivanovich · Dec 18, 2014

C++ standard says

11.1 A member of a class can be
(1.1) — private; that is, its name can be used only by members and friends of the class in which it is declared.

i.e. the access specifier is applied to the name, not the executable code. This makes sense if you think about it, since access specifiers are a compile-time construct.