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 protected
less 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 use protected
. I just find I need it less and less.)
I am curious of what other people will answer to that.
As well as for the accessors paradigm, you may declare them private and use protected Getter and Setter methods. If your base class implementation changes, you only have those getter and setter to modify.
If you think child classes will need access to those variables later then yes, make them protected.
There is no drawback, as long as the aforementioned condition is met.
If you want to take the extra step and protect your variables from outside access, you could always create private member variables and then use protected methods to access/modify those private variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With