2

I have a C++ class (Class D) that is a decorator of another class (Class B). Class D inherits from B and also requires an instance of B to construct that it keeps track of. Class D overrides all methods in B and instead calls the same functions on it's own instance of B. My worry is in maintaining this. If someone edits class B and adds a new function, they need to ensure that they add that function to class D as well, or it will break the pattern. Is there a way I can check at compile time that class D overrides all methods from class B? I'm working in C++.

Code sample:

class B
{
 public:
  B();
  void methodA() {std::cout << "A" << std::endl;};
  void methodB() {std::cout << "B" << std::endl;};
};

class D : public B { public: D(B* b) { bptr_ = b; } void methodA() override { bptr_->methodA(); }

void methodB() override { bptr_->methodB(); }

void specialDFunction() {/do something/}; private: B* bptr_; }

1 Answers1

6
  • Convert B into an abstract class (an interface) with only pure virtual methods. The implementation code for the methods should be in a derived class C.

  • Now C and D are both deriving from B, and code which uses B can get either a C or D object. Whenever B gets extended by another pure virtual method, the compiler will tell you to extend C and D as well.

Doc Brown
  • 218,378