Asking this question because I feel that member variables of my base will be needed later in derived classes. Is there a drawback of making them protected?
EDIT: Edited to better show my intention.
EDIT: @sbi : Is this also wrong?
This class will be used for error recording and retrieving in other classes. Is it better to derive from it or use an object of it – I don’t know. But I think the getter and setter methods are what this class is all about.
class ErrorLogger
{
public:
//Making this function virtual is optional
virtual void SetError(const char*, ...);
const char* GetError() const;
protected:
char* z_ErrorBuf;
};
Encapsulation is one of the main features of OO. Encapsulating your data in classes means that users of the class can not break the class’ data’s invariants, because the class’ state can only be manipulated through its member functions.
If you allow derived classes access to their base class’ data, then derived classes need to take care to not to invalidate the base class’ data’s invariants. That throws encapsulation out of the window and is just wrong. (So do getters and setters, BTW.)
I find myself using
protectedless and less over the years, even for member functions. If a class fully implements a simple concept, then all of its state should be manipulatable through its public interface. If derived classes need “back doors” to sneak in, then I usually question my design. (Which isn’t to say I never useprotected. I just find I need it less and less.)