Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common protected data member in base class?

Tags:

c++

I have a base class and several derived classes. The derived classes use some common data, can I just put those common data as protected member of the base class? I know the protected member breaks encapsulation sometimes, so I wonder if there is any good approach.

Here is a specific example:

class Base{
public:
   virtual void foo() = 0;
   void printData();
protected:
   std::vector<std::string> mData;
}

class Dr1 : public Base{
public:
   virtual void foo(); //could change mData
}

class Dr2 : public Base{
public:
   virtual void foo(); //could change mData
}

If I put mData into Dr1 and Dr2 as private member, then I need to put it in both of them, and I can not have printData() in Base since printData() need access to mData unless I make printData() virtual and have identical function in both Dr1 and Dr2, which doesn't make much sense to me.

Is there a better way to approach this without using protected member? Thank you.

like image 751
EXP0 Avatar asked Jun 10 '10 21:06

EXP0


1 Answers

This is open to considerable argument. Allowing data to be protected was added to C++ largely because Mark Linton wanted it for the Interviews Windowing library he was designing. It seemed to fit reasonably well with the rest of the design of C++, so (apparently) Bjarne went along with the idea. After a few years, Mark had banned all use of protected data members in Interviews because of the number of bugs that had resulted from their use. Some time after after that, Barbara Liskov gave a talk about both theoretical and practical problems with the whole notion.

In The Design and Evolution of C++, Bjarne concludes that: "In retrospect I think that protected is a case where I let 'good arguments' and fashion overcome my better judgment and my rules of thumb for accepting new features."

Bottom line: I'd have second and third thoughts about making your data protected. It may look like a good idea now, but maintenance may be a rather different story.

like image 144
Jerry Coffin Avatar answered Sep 18 '22 10:09

Jerry Coffin