nullzero
nullzero

Reputation: 13

Inheritance without containing?

I have class A. And I have class B. And I have many-many classes derived from class B.

I want to achieve this: derivatives of B should have access to the protected variables of A. Whithout each of them containing an instance of A, which would need a lot of memory. So I guess public inheritance is not a good idea this time. How do I solve this? Thanks!

Upvotes: 1

Views: 100

Answers (3)

Mark B
Mark B

Reputation: 96281

From what I understand children of B are unrelated to class A and as such should not have access to non-public parts of A.

The right way to get access to A's data within B child classes is through A's public interface. If such public interface isn't adequate then that's a signal that either you're trying to do something that's a poor design, or that A's public interface needs to be improved.

Upvotes: 0

Erik
Erik

Reputation: 91300

You could do it with friend and accessor functions. This does trust B to stay off A's privates - don't see a good way to let only B and subclasses access only protected members of A unless there's an inheritance relationship between A and B.

class A {
friend class B;
protected:
  int X;
};


class B {
protected:
  static int getX(A const & a) { return a.X; }
};

class C : public B {
public:
  void foo(A const & a) { int bar = getX(a); }
};

Upvotes: 5

Oswald
Oswald

Reputation: 31685

Make the classes that are derived from B friends of A.

Upvotes: 0

Related Questions