Reputation: 25
How can I reach privateMember
without friend
in all of the derived classes?
class parent{...}; //a virtual class
class A: public parent{...};
class B: public parent{...};
class C: public parent{...};
class D: public parent{...};
class E: public parent{...};
...
//each has a function, that want access to privateMember
class MyClass{
int privateMember;
friend parent;
//I know it doesnt't work, but this shows the best what I want
}
Upvotes: 0
Views: 83
Reputation: 47762
Leave it as is (with friend class parent
) and add an accessor function to parent
that A
, B
,... will use. It would be protected, so functions from outside the hierarchy can't use it.
class parent {
protected:
static int& getPrivate( MyClass & c ) { return c.privateMember; }
...
};
You have to do this, because friendship doesn't extend to derived classes.
Upvotes: 3
Reputation: 96261
The simple answer here is to not go mucking with the internal state of other classes. Instead, use their public API. This way you never have to worry about locking yourself into an implementation AND you avoid a wide variety of potential problems with inadvertently breaking class invariants when you modify the variable.
Upvotes: 0
Reputation: 1011
You could create a getter function, that would return a privateMember:
int getPrivateMember() const { return privateMEmber; }
This must be a public method of course.
Upvotes: 0