CW Holeman II
CW Holeman II

Reputation: 4961

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();
}

Upvotes: 0

Views: 332

Answers (4)

Motti
Motti

Reputation: 114725

The simplest solution would be to remove m_MAX from the class and put it in an anonymous namespace in the .cpp file in which both Q::ask and UI::run are defined. Since it's a static const you gain nothing by having it as part of the class declaration.

Upvotes: 0

Reunanen
Reunanen

Reputation: 8001

Yep, declaring UI as friend of Q is the answer to what you ask. An alternative solution could be to make Q a private nested class of UI:

#include <vector>

class UI {
private:
    class Q {
    public:
        static int const m_MAX=17;
        int ask(){return 4;}
    };

    std::vector<Q*> m_list;

public:
    void addNewQ(){m_list.push_back(new Q);}
    int run(){return Q::m_MAX==m_list[0]->ask();}
};

int main()
{
    UI ui;
    ui.addNewQ();
    ui.addNewQ();
    int status = ui.run();
}

Now, nothing of Q is visible outside UI. (Which may or may not be what you want.)

Upvotes: 0

anon
anon

Reputation:

A simple solution - make m_MAX and ask() private and make UI a friend of Q.

Upvotes: 2

DeusAduro
DeusAduro

Reputation: 6076

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.

Upvotes: 5

Related Questions