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


since i'm newbie in c++, here goes!

i have base class (i'm not using inheritance anywhere) 2 objects 2 other classes. need have access private member other in 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 this???     } }; 

how can have access of m_member1 myclass1 in myclass2? :)

(i want avoid inheritance, because on code myclass1 , 2 not base class...)

thanks

there many ways it.

to allow access m_member1 @ all, make m_member1 public. or declare friend of myclass1, 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 give myclass1 public accessor:

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

then allow m2 reach m1, give m2 pointer m1:

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

or relay value of m_member1 through base upon request of m2, answer getting long.

(and once you're comfortable of this, should take note sum_members_because_yes belongs in base.)


Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -