Let’s assume I want a single class Child and only this class to inherit from Father
and grant Child access to Fathers data members. Apart from this no one should inherit from father to get to its internals, hence I keep the data of Father private
Edit: I opted against protected since I want the data hidden. Some people advocate this as good practice but perhaps its a little too dogmatic: (e.g. Herb Sutter in http://drdobbs.com/184403867) Actually the class should be extended only once. Hence prohibiting inheritance as Steve Jessop pointed out would be an option but I think the cost of that (virtual etc.) is going too far for what I need.
Code would look like this:
class Father{
friend class Child;
public:
//functions
private:
int mData;
}
class Child: public Father{
public:
void changeData(int val){mData=val;}
}
Am I running into some serious trouble here or is this a valid decision assuming that inheritance was a good decision in the first place.
This doesn’t actually prevent anyone else using
Fatheras a base class, it just prevents them from accessingmDataif they do.If that’s what you want (
Childhas privileged access toFather, that other classes don’t have, and the fact thatChildhappens to also have a base classFatheris unrelated), fine.If you additionally forbid anyone else from using
Fatheras a base class (either via documentation alone, or using the trick with the virtual base class), then the use offriendbecomes a bit pointless. You might as well just makemDataprotected instead of private, that’s exactly what protected is for.