C++ Functions for an Abstract Base Class

abstract classc

Suppose I want to have an inheritance hierarchy like this.

class Base

class DerivedOne : public Base

class DerivedTwo : public Base

The base class is not meant to be instantiated, and thus has some pure virtual functions that the derived classes must define, making it an abstract base class.

However, there are some functions that you would like your derived classes to get from your base class. These functions modify private data members that both DerivedOne and DerivedTwo will have.

class Base {
public:
      virtual void MustDefine() =0; // Function that derived classes must define
      void UseThis(); // Function that derived classes are meant to use
};

However, the UseThis() function is meant to modify private data members. That's where the question comes in. Should I give the Base class dummy private data members? Should I give it protected data members (and thus the derived classes won't declare their own private data members). I know the second approach will decrease encapsulation.

What is the best approach to a situation like this? If a more detailed explanation is needed I'd be happy to provide it.

Best Answer

If those member variables are supposed to exist in all derived classes then you should declare them in the base class. If you are worried about encapsulation, you can make them private and provide protected accessor methods for derived classes.