Search code examples
c++classabstractradix

c++ abstract base class private members


Just wanted some clarification. Should abstract base classes never have private members? For example

class abc{
public:
  virtual void foo()=0;
private:
  int myInt;
}

you can never access myInt since you cannot create an instance of abc and it will not be in a derived class since its private. Is there any situation where you would use private members in abstract base classes or is this just wrong?


Solution

  • In C++ you can have an abstract class that has non pure virtual methods. In that case, and depending on the design it can make sense to have private members:

    class base {
       std::string name;
    public:
       base( std::string const & n ) : name(n) {}
       std::string const & getName() const { return name; }
    
       virtual void foo() = 0;
    };
    

    That code ensures that every object that derives from base has a name, that is set during construction and never changes during the lifetime of the object.

    EDIT: For completion after Charles Bailey reminded me of it in his answer

    You can also define pure-virtual functions, and in that case, private attributes could also make sense:

    // with the above definition of base
    void base::foo() {
       std::cout << "My name is " << name << std::endl;
    }