views:

206

answers:

4

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

C++0x is OK.

+5  A: 

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.

DeusAduro
Changing Q to: class Q {private: static int const m_MAX=17; int ask(){return 4;} friend class UI;};Produced no errors. How does you note about forward declaration apply?
C.W.Holeman II
Hmm maybe I was wrong there I assumed that you would get an unknown symbol error. But maybe the friend statement acts like a forward declaration. Good that it works though.
DeusAduro
+2  A: 

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

anon
A: 

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.)

Pukku
A: 

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.

Motti