Abstract base class / derivation question?

I have an abstract base class.

1
2
3
4
  class A {
  public:
    virtual void message() const = 0;
  };


And I want to derive eight class's from this base class, but two classes output the same message, another three output the same message, and finally the last three output their own unique message. How can I derive these eight classes from this base class without having repeated implementations of message()?

I was thinking of something along the lines of:

1
2
3
4
  class SameTwoMessage : public A {
  public:
    virtual void message() const;
  };


and deriving two classes from this SameTwoMessage class, and then:

1
2
3
4
  class SameThreeMessage : public A {
  public:
    virtual void message() const;
  };


and deriving three classes from this SameThreeMessage class, while the rest of the derived classes will implement their own unique version of message().

Would this be the ideal way to go about this?
Last edited on
Yes, an inheritance hierarchy is probably okay.

In my opinion, 8 derived classes is undesirable already, because it implies eight fundamentally different implementations of the same thing, which is unusual. If this is not the case, another solution might be better. For example, if only the messages differ, it might be better to reify the concept of a "messenger" and make each A require one:

1
2
3
4
5
6
7
8
9
10
11
struct A {
  explicit A(messenger m = default_messenger())
    : messenger_(m) {};

  virtual ~A() = default;

  virtual void message() const // can even be final, if appropriate
  { messenger_.send_message(); } // whatever
  
  // ...
};
Last edited on
Topic archived. No new replies allowed.