Class derivation / Shared functions question?

So if I have a pure abstract base class as so:

1
2
3
4
5
class A {
public:
   virtual void message1() const = 0;
   virtual void message2() const { //show message };
};


and I have three derived classes (B : public A, C: public A, D: public A), where both B and C have the same message1() implementation, and D has an unique implementation of message1().

All three share the same message2() implementation.

Is there a way I can implement B and C message1() only once using inheritance?

Last edited on
Using inheritance, something like this, perhaps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <string>

struct A
{
    virtual void message_1() const = 0 ;
    virtual void message_2() const = 0 ;

    // ...
};

struct A_msg2_impl : A
{
    virtual void message_2() const override { std::cout << "message_2 impl\n" ; }
};

struct A_msg1_and_2_impl : A_msg2_impl
{
    virtual void message_1() const override { std::cout << "default message_1 impl\n" ; }
};

struct B : A_msg1_and_2_impl { /* ... */ };
struct C : A_msg1_and_2_impl { /* ... */ };

struct D : A_msg2_impl
{
    virtual void message_1() const override { std::cout << "different message_1 impl\n" ; }
};
Topic archived. No new replies allowed.