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_;
}


  • Alternatively I could just not have D not inherit from B, but that removes my ability to treat any B as a D. – Alexis Winters May 18 '21 at 21:30
  • 1
    Close-voter and downvoter, not every question with code in it is a "coding" question - this is clearly a question about class design and how to use inheritance, which are on-topic here. Please help to fight the impression question that almost every question, even if it is a valid one, here on this site gets arbitrary close votes and downvotes. – Doc Brown May 19 '21 at 05:10

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
  • 199,015
  • 33
  • 367
  • 565