简体   繁体   中英

C++ Access private member from a derived class to another derived class (both have the same base class)

So I have a base class with two derived classes (deriv1 and deriv2). On the deriv2 class I need to access a private member from deriv1... How can I do this?

Sample code:

    class base
    {
    private:

    public:
        base() {};
        ~base() {};
    };

    class deriv1 : public base
    {
    private:
        int m_member1;
    public:
        deriv1() {};

        ~deriv1() {};
    };

    class deriv2 : public base
    {
    private:
        int m_member2;
    public:
        deriv2() {};

        ~deriv2() {};
    int sum_members_because_yes(void)
    {
        return (deriv1::m_member1 + m_member2); // <---- :((
    }
};

How can I access a private member from another derived class? I was trying to avoid using friend functions, or changing the private member to public... What do you advice?

Thank you! :)

You cannot access deriv1 private data members from deriv2 .
You have two options to overcome that :

Do a getter to access your m_member1 in your deriv1 class.

class deriv1 : public base
{
private:
    int m_member1;
public:
    int get_member1() const { return m_member1; }
[...]
}

Use protected on m_member1 and make your deriv2 also derived from deriv1 .

 class deriv1 : public base
 {
 protected:
   int m_member1;
   [...]
 }

class deriv2 : public base, public deriv1
{ 
  [...]
}

Use the option which seem to be coherent with your context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM