friend classes and list<ClassSomething*>

Hey
So i have class X with a list of <ClassY*> (There are classes inheriting from Y) and i want to write a function that returns the list (A member function of class X). What should it return?
p.s Class Y is a friend class of class X (And also class X is a friend of class Y)

Thank you in advance
Hi there,

Your question is kind of answering itself:

Aibsr wrote:
So i have class X with a list of <ClassY*> (There are classes inheriting from Y) and i want to write a function that returns the list (A member function of class X).


1
2
3
4
5
6
7
8
9
10
#include <list>

class X
{
    public:
        std::list<Y*> get_list() { return _list; }

    private:
        std::list<Y*> _list;
}


Hope that helps.

All the best,
NwN
X and Y don't need to be friends with each other, why did you make them as such?
NwN thank you! I wasn't sure if i can return list<Y*> in a friend class of Y.

LB because X=Customers and Y=Apartments, each customer has a list of apartment, and each apartment has to know what customer owns it. Is there a more efficient way to do so?
You don't need to use the "friend" keyword at all.
each customer has a list of apartment, and each apartment has to know what customer owns it


That seems like a bad design-decision to me. Think about it: A customer owns an apartment, the apartment itself doesn't need to know who owns it, in fact, an apartment can't really know who owns it because, well, it's an apartment.

Suppose that the apartment has a doorbell which requires the owners name, you would think "then the apartment needs to know the owner". Wrong, the owner puts his own name on the doorbell of his apartment.

In code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class doorbell_t
{
    public:
        std::string name;
};

class apartment
{
    public:
        doorbell_t doorbell;
};

class customer
{
    public:
        std::string name;
        add_apartment(apartment& a)
        {
                a.doorbell.name = name; //the customer puts his name on the doorbell
                owned_apartments.push_back(a);
        }

    private:
        std::vector<apartment> owned_apartments;
};


Hope that makes sense to you. Let us know if you require any further help.

All the best,
NwN
This is for a question in an exam and the question literally says that i need to implement a function that returns the owners name. in this case friend class is the best option isn't it?
If you really must, I think a friend class would be the tidiest solution, yes.

All the best,
NwN
Thank you for your help:)
Topic archived. No new replies allowed.