Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 534
Olumide Avatar asked Dec 18 '14 00:12

Olumide


People also ask

Can we access private method from outside class Java?

We can call the private method of a class from another class in Java (which are defined using the private access modifier in Java). We can do this by changing the runtime behavior of the class by using some predefined methods of Java. For accessing private method of different class we will use Reflection API.

Can we access private function of class with its object?

Private: The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class.

How do you call a private member function in C++?

Either make the function itself public or add another public function to call the private one: class cricket { private: // ... void cal_penalty_impl() { // Your original code goes here // ... } public: // ... void cal_penalty() { cal_penalty_impl(); } };


2 Answers

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.

like image 62
sdzivanovich Avatar answered Sep 29 '22 02:09

sdzivanovich


Yes it is permissible, and it works.

C++ Programming by Bjarne Stroustoup

C++ protects against accident rather than deliberate circumvention (fraud)

Sure, you cannot directly/easily call private methods outside the class, but if you are making enough efforts, C++ will allow it.

like image 24
Pranit Kothari Avatar answered Sep 29 '22 01:09

Pranit Kothari