Home > Blockchain >  Only allow further inheritance from child class
Only allow further inheritance from child class

Time:10-05

Context: I'm doing some internal cleanup to move away from large & unwieldy data structures to more well-defined data structures.

Current

I have a class that does something like this:

class Base {
public:
  virtual int DoStuff(BigType input);
};

Calling code:

std::vector<Base*> bases;
BigType input;

for (const auto& base : bases) {
    base.DoStuff(input);
}

Child classes currently look like this:

class Child : public Base {
  int DoStuff(BigType input) const override {
    // do stuff
  }
};

Attempted

I added an intermediate interface:

template <typename SmallType>
class FocusedBase : public Base {
public:
  int DoStuff(BigType input) const override {
    return DoStuff(SmallType(input));
  }

  virtual int DoStuff(SmallType input);
};

Child classes now look like this. Note that SmallType may differ across child classes:

class Child : public FocusedBase<SmallType> {
  int DoStuff(SmallType input) {
    // do stuff
  }
};

Calling code remains the same.

Issue

I'd like to have new classes inherit from FocusedBase only, not Base. Any thoughts on how to do so?

CodePudding user response:

If you want to disallow inheriting from Base directly you can make Base::Base() private and make FocusedBase a friend:

struct Base {
    private:
    Base() = default;
    friend class FocusedBase;
};

struct FocusedBase : Base {};

struct Foo : Base {};

struct Bar : FocusedBase {};

int main() {      
    //Foo f;  // error
    Bar b;  // ok
}
  •  Tags:  
  • c
  • Related