Search code examples
c++oopfriend

What happens when Classes that are friends have same name member variables


In C++, what happens when I have the following

class House
{
public:
    House();
    ~House();

private:
    int* m_peopleInside;

friend class Room;
}; 

and then in the constructor of House this is set

m_peopleInside = new int[5];
m_peopleInside[4] = 2;

and

class Room
{
public:
    Room();
    ~Room();

    Update();

private:
    int* m_peopleInside;
}; 

Then in the Room.Update() I use m_peopleInside something like this.

&m_peopleInside[4];

It's my understanding that the friend class will allow the Room class to access private members of the House class. So which m_peopleInside would be used?

I should add that in this case, m_peopleInside is being used as an array.


Solution

  • It's an instance variable. So it needs an instance to act on. If no instance is provided, then it is the same as this->m_peopleInside, which means it refers to the instance on which the function was called. So, for example, if this is your function:

    void Room::Update() {
        // these two are the same, they null the member of the Room object
        m_peopleInside = nullptr;
        this->m_peopleInside = nullptr;
    
        House h;
        // should be pretty obvious what this does
        h.m_peopleInside = nullptr;
    }