Search code examples
c++compositionprivate-membersobject-composition

C++ access private member in composition of two classes from base class


Since I'm a newbie in C++, here it goes!

I have a base class (I'm not using inheritance anywhere) with two objects from two other classes. I need to have access from a private member to the other in another class.

class base
{
private:
    myClass1 m1;
    myClass2 m2;
public:
    base() {};
    ~base() {};
};

class myClass1
{
private:
    int m_member1;
public:
    myClass1() {};

    ~myClass1() {};
};

class myClass2
{
private:
    int m_member2;
public:
    myClass2() {};

    ~myClass2() {};

    int sum_members_because_yes(void)
    {
        return (myClass1::m_member1 + m_member2); //HOW CAN I DO THIS???
    }
};

How can I have access of m_member1 from myClass1 in myClass2? :)

(I want to avoid inheritance, because on my code the myClass1 and 2 is not a base class...)

Thanks


Solution

  • There are many ways to do it.

    To allow access to m_member1 at all, you could make m_member1 public. Or you could declare something a friend of myClass1, like this:

    class myClass1
    {
    private:
      int m_member1;
      ...
      friend class base;
    };
    

    or this:

    class myClass1
    {
    private:
      int m_member1;
      ...
      friend class myClass2;
    };
    

    or this:

    class myClass1
    {
    private:
      int m_member1;
      ...
      friend class int myClass2::sum_members_because_yes(void);
    };
    

    Or you could give myClass1 a public accessor:

    class myClass1
    {
      ...
    public:
      ...
      int get_m_member1() const
      {
        return(m_member_1);
      }
    };
    

    Then to allow m2 to reach m1, you could give m2 a pointer to m1:

    class myClass2
    {
      ...
    public:
      myClass1 *pm1;
    };
    
    class base
    {
      ...
    public:
      base()
      {
        m2.pm1 = &m1;
      };
    };
    

    or you could relay the value of m_member1 through the base upon the request of m2, but this answer is getting long.

    (And once you're comfortable with all of this, you should take note that sum_members_because_yes really belongs in base.)