0

Suppose I have four classes, A1, B1, B2, and C1. A1 is the base class, B1 and B2 inherit publicly from A1, and C1 inherits publicly from B1 and B2. B1 and B2 are virtual classes.

Example

Now, suppose I need a member function defined in A1. Is it possible to make the member function inaccessible to B1 and B2 but accessible to C1? If the member function protected or public, then B1 and B2 still have access to it, so that doesn't work. If it's private, then C1 doesn't have access to it, so that doesn't work, so I'm kind of stuck here. I'm still quite inexperienced in C++, and I'm not sure if friend functions or friend classes make sense in this situation. If not, is this even possible?

JohnTravolski
  • 131
  • 1
  • 1
  • 6
  • 1
    In `A1`: `friend class C1;` – aschepler Jul 02 '17 at 18:55
  • Would you please explain why you think so? I'm still new to programming in general, and I'm willing to learn. – JohnTravolski Jul 02 '17 at 19:07
  • Can you provide any context in which this is wanted? If there is behaviour which B1 and B2 should not have but C1 should, why do they inherit from A1 in the first place? – Aziuth Jul 02 '17 at 19:10
  • Class A1 contains variables that need to be read-only to B1 and B2, regardless of whether or not the corresponding B1/B2 member functions are declared const, yet C1 needs to be able to change these member variables. – JohnTravolski Jul 02 '17 at 19:56

1 Answers1

1

From a design point of view, such request looks a rather suspicious.

With that being said, technically you can consider making C a friend of A:

class C;

class A
{
private:
    int m_x = 0;
    friend class C;
};

class B : public A
{
private:
    void f()
    {
        m_x = 1; //error
    }
};

class C : public B
{
private:
    void g()
    {
        m_x = 1; //ok
    }
};
AlexD
  • 32,156
  • 3
  • 71
  • 65