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

52 views Asked by At

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?

2

There are 2 answers

0
Holt On BEST ANSWER

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_.

0
Jarod42 On

You may do the check in A directly, something like:

class A {
public:
    A(int size);
    virtual ~A() = default;

    void doSomething(int inputSize)
    {
        if (!checkSize(inputSize)){
           std::cerr<<"wrong inputSize!"<<std::endl;
           return;
        }
        doSomethingWithChekedSize(inputSize);
    }

protected:
    virtual void doSomethingWithChekedSize(int inputSize) = 0;
    virtual bool checkSize(int inputSize);
private:
    int size;
};