Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to make member variables protected? [closed]

Tags:

c++

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;
};
like image 797
nakiya Avatar asked Oct 14 '10 12:10

nakiya


3 Answers

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.)

like image 156
sbi Avatar answered Nov 15 '22 19:11

sbi


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.

like image 42
Benoit Avatar answered Nov 15 '22 18:11

Benoit


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.

like image 21
Justin Niessner Avatar answered Nov 15 '22 20:11

Justin Niessner