Search code examples
c++c++11encapsulation

How can/should C++ static member variable and function be hidden?


m_MAX and ask() are used by run() but should otherwise not be public. How can/should this be done?

#include <vector>
class Q {
public:
    static int const m_MAX=17;
    int ask(){return 4;}
};
class UI {
private:
    std::vector<Q*> m_list;
public:
    void add(Q* a_q){m_list.push_back(a_q);}
    int run(){return Q::m_MAX==m_list[0]->ask();}
};
int main()
{
    UI ui;
    ui.add(new Q);
    ui.add(new Q);
    int status = ui.run();
}

Solution

  • You could define both m_MAX and ask() within the private section of class Q. Then in Q add: "friend class UI". This will allow UI to access the private members of Q, but no one else. Also note that UI must be defined before the "friend class UI" statement. A forward declaration will work.