vendredi 24 février 2023

Correct way to 'glue' two class implementation in C++

I am new to C++, now I have a problem needs to solve. I have a class in A library and the same class in B library, C function is the only connection between A and B, I need to pass the class implemented in A and run it in B, what is the best way to do it in C function? In library A

class ClassAImp : public ClassA
{
public:
    ClassAImp();
    ~ClassAImp();
    
    void Setup() override {/* do some setup */};
    void TearDown() override {/* do teardown stuff */};
    void runMethodA(void* ptr) override {/* do method A stuff */};
}

class ClassA
{
public:    
    virtual void Setup() = 0;
    virtual TearDown() = 0;
    virtual runMethodA(void* ptr) = 0;
}

In library B

class ClassB
{
public:    
    virtual void Setup() = 0;
    virtual TearDown() = 0;
    virtual runMethodA(void* ptr) = 0;
}

Currently what I am doing in C is

class ClassBImp : public ClassB
{
public:
    ClassBImp(std::shared_ptr<ClassA> _classAObj) : classAObj(_classAObj) {};
    virtual ~ClassBImp();
    
    void Setup() override { if (classAObj) classAObj->Setup(); };
    void TearDown() override { if (classAObj) classAObj->TearDown(); };
    void runMethodA(void* ptr) override { if (classAObj) classAObj->runMethodA(ptr); };
private:
    std::shared_ptr<ClassA> classAObj;
}

And pass the ClassBImpPtr (as std::shared_ptr) to the B library.

I don't have any control over library A or B, only can do things in C and pass the implemented object back to B. Is it the right way of doing things in C++ (11?) Is there a better way of doing it?

Aucun commentaire:

Enregistrer un commentaire