0

I think I really should explain myself about my question :p

So, I have a class c (let's start from the end), in this class c I want to use an attribute which is defined in class A. But my class c does not inherit from A, it is a friend of class b which inherit from A.

If i can, how cans i access this attribute ?

A little example in some kind of c++

class A
 protected:
   type THE_Attribute

class B: class A
 ...
 public:
   friend class c<type>;

class c:
  ....
  public:
   Need(THE_Attribute);

I hope you understood my question, thanks :)

1
  • Quick answer: You can't. Not unless you inherit class C from A then use getters to use that variable. Nov 27, 2015 at 18:16

1 Answer 1

0

You have to expose the member in class B:

#include <iostream>

class A
{
    public:
    void print() {
        std::cout << value << '\n';
    }

    protected:
    int value = 0;
};

class B : private A
{
    friend class C;

    public:
    using A::print;

    private:
    int get_value() const { return A::value; }
    void set_value(int value) { A::value = value; }
};

class C
{
    public:
    void modify(B& b) { b.set_value(42); }
};

int main()
{
    B b;
    b.print();
    C c;
    c.modify(b);
    b.print();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.