Search code examples
c++abstract-classvirtualpure-virtual

C++ Automatically call check methods from parent abstract class in implemented pure virtual methods?


I have this abstract class in C++:

class A {
public:
  A(int size);
  virtual void doSomething(int inputSize) = 0;
protected:
  virtual bool checkSize(int inputSize);
private:
  int size;
}

A::A(int size) : size(size){}
bool A::checkSize(int inputSize) { return size == inputSize; }

Now, what I want to guarantee is that for each class B derived from A doSomething begins like this:

class B : public A{
  void doSomething(int inputSize);
}

void B::doSomething(int inputSize){
  if(!checkSize(inputSize)){
     std::cerr<<"wrong inputSize!"<<std::endl;
     return;
  }
  //do something...
}

How can I guarantee that each derived class from A implements doSomething starting in that way?


Solution

  • You split doSomething into two parts:

    class A {
    public:
      void doSomething(int inputSize) {
        if (!checkSize(inputSize)){
           std::cerr << "wrong inputSize!" << std::endl;
           return;
        }
        doSomething_(inputSize);
      }
    protected:
      virtual void doSomething_(int) = 0;
    };
    

    And in B you only implement doSomething_.