1

Could you give me advice how should I properly structure my code? I am trying to sort students, and to do it I need access to Database object and also private member of Student - index. Now I get error:

error: ‘Database’ has not been declared friend void sortStudents(Database db);

but If I reorder classes I will get:

Student’ was not declared in this scope std::vector data;

What is the proper solution?

class Student
{
    private:
        int _index {0};
    public:
        friend void sortStudents(Database db);
};

class Database
{
    private:
        std::vector <Student> data;
    public:
        friend void sortStudents(Database db);
};


void sortStudents(Database db)
{
    std::sort((db.data).begin(), (db.data).end(), 
             [](const Student& leftSide, const Student& rightSide)
             { return leftSide._index < rightSide._index; }
             );
}
flamingo
  • 148
  • 1
  • 11
  • 2
    Also `sort` returning `void` on a function taking a database by value? – Matthieu Brucher Jan 19 '19 at 20:15
  • At the beginning I put sort as a member of Database class. What is your suggestion? Does it mean that the only option for me is forward declaration? – flamingo Jan 19 '19 at 20:22
  • It's forward declaration and passing a reference. Or even better, make `sortStudents` part of the database. – Matthieu Brucher Jan 19 '19 at 20:23
  • 2
    @flamingo I don't get why you need that `friend` declaration at all. – πάντα ῥεῖ Jan 19 '19 at 20:23
  • 1
    @drescherjm there is the issue of all data being private because there is no comparison operator or accessor. Well, not a great design I'd say. – Matthieu Brucher Jan 19 '19 at 20:24
  • Hi, I am trying to experience some mistake and learn not to do it more ;) @MatthieuBrucher does it mean that I can better structure that code? for example in one class? or division to two classes is ok in that situation? – flamingo Jan 19 '19 at 20:29
  • The answer to the question you asked, is that you are trying to use a Database variable by value (without * or &) before declaring the Database class. You should add a * or & to the sortStudents function parameter, and forward-declare the Database class by putting “class Database;” before the start of the code. (What the others were saying, was that if you don’t put * or &, the Database that your function tries to sort will be a copy, instead of the original.) – Anonymous1847 Jan 19 '19 at 23:14
  • @Anonymous1847 Thank you for good explanation – flamingo Jan 20 '19 at 08:53

0 Answers0