Quantcast
Channel: User Peter - Reinstate Monica - Stack Overflow
Viewing all articles
Browse latest Browse all 223

Answer by Peter - Reinstate Monica for Correct way to 'glue' two class implementation in C++

$
0
0

I assume you are unhappy about the code duplication (stupid repetitions!). Some duplication is unavoidable with delegation (here: Let an existing implementation —ClassBImp— do another interface's —ClassA's — job).

But if you simply inherit from both the interface and the implementation you don't have to create a separate ClassAImp object — your class is-aClassB—, and the forwarding is arguably simpler because you just qualify the function you call to do the work with the implementation class name:

struct ClassBImp: public ClassAImp, public ClassB{    void Setup() override { ClassAImp::Setup(); }    void TearDown()  override { ClassAImp::TearDown(); }    void runMethod(void* ptr)  override { ClassAImp::runMethod(ptr); }};

It doesn't get any simpler than that.

Let's assume a function in Library B which expects a shared pointer to a ClassB (and I further assume that this function most likely calls member functions of the ClassB object we passed a pointer to):

static void Library_B_Callback(std::shared_ptr<ClassB> bPtr) {     std::cout << "DoSomething<std::shared_ptr<ClassB>>\n";     if (bPtr)    {        std::cout << "DoSomething<std::shared_ptr<ClassB>>: Calling bPtr->runMethod()\n";        // do something with that pointer        bPtr->runMethod(nullptr);    }}

Then you can call it with

int main(){    Library_B_Callback(make_shared<ClassBImp>());}

That is, you can provide a shared pointer to a derived when a shared pointer to base is expected, just like regular pointers; they are covariant.


Viewing all articles
Browse latest Browse all 223

Trending Articles