I am close to completion of my first OOP project, coming from a C background. I was wondering a design issue related to some ifstream object that I use in the base class to open a file. After that I would like to use the same stream to do further operation by the derived classes. I defined only this member as a protected one so I could reach that in the derived classes, protected breaks the encapsulation(I would like to earn good habits), should I define some getter function to return a reference to a stream object? Since the ifstream objects are not copiable, that might be a problem, first thing I see…
Best,
Umut
protectedis ideal for preserving encapsulation, if it’s integral to your design that the derived classes have the same I/O functionality as the base class.Encapsulation does not mean everything has to be
private, it means that each data or code member of a given class is visible only to the minimal set of class users to achieve the class’s designed purpose. In other words, don’t make everythingpublicjust because that makes it easier to code.You would only need a
publicgetter if you wanted to expose the I/O function of the base and derived classes to code outside of the hierarchy. Returning a reference does not imply any copy, by the way.