Search code examples
c++methodsstaticprivateinvoke

Access private static method from outside the class C++


How exactly can you access a private static method from outside the class. Say, I have a class

    Class ABC {
    private:
        static void print(string str) {
            cout << "It works!!!" << endl;
        }
    };

Now, I just to call print() function say from another function like:

    void doSomething() {
         string str = "1776a0";
         // Call to print() here
    }

I have searched the internet and stackoverflow for such a problem but I couldn't find much. So, please point me in the right direction as to if this is possible or not and if so how to do it.

I am currently using GCC.

Thank you all in advance.


Solution

  • You can't. That is exactly what private means. If it is intended to be callable from outside the class, make it public.

    Instead of making it public you could call it from another function that is publicly accessible. This other function could either be a public member of ABC, or a friend function.

    Both cases require changing the class definition of ABC.

    If the other function just does nothing besides call print() then you have achieved the same effect as making print() public. But presumably print is private for a reason, e.g. it relies on some preconditions. You could make the other function allow for that. For example:

    void abc_printer(string printer_name, string str_to_print)
    {
        open_printer(printer_name);          
        ABC::print(str);                         
        close_printer();
    }
    

    and inside the class definition of ABC:

    friend void abc_printer(string, string);