Common protected data member in base class?

Posted by EXP0 on Stack Overflow See other posts from Stack Overflow or by EXP0
Published on 2010-06-10T21:37:35Z Indexed on 2010/06/10 21:52 UTC
Read the original article Hit count: 161

Filed under:

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.

© Stack Overflow or respective owner

Related posts about c++