vendredi 22 septembre 2023

In the context of inheritance in C++, how can a function in the derived class be invoked before the execution of the base class constructor?

this is an example program to demonstrate adapter pattern.
In the context of inheritance in C++, how can a function in the derived class be invoked before the execution of the base class constructor?

AdapterInterface(int d, double r) : LegacyInterface(_w, _h)

I was looking for a solution to execute diagToRectConverter before LegacyInterface(_w, _h) call.

#include <iostream>
#include <cmath>

// Desired interface (calculate rect based on diagonal and ratio)
class NewInterface
{
public:
    NewInterface() { std::cout << "NewInterface ctr" << std::endl; }
    virtual void draw() = 0;
};

// Legacy component (Adaptee)
class LegacyInterface
{
public:
    LegacyInterface(double w, double h) : _w(w), _h(h) { std::cout << "LegacyInterface ctr" << std::endl; }

    void oldDraw()
    {
        std::cout << "--LegacyInterface--" << std::endl;
        std::cout << "Width    : " << _w;
        std::cout << "  Height   : " << _h << std::endl;
    }

private:
    double _w;
    double _h;
};

// Adapter wrapper
class AdapterInterface : public NewInterface, private LegacyInterface
{
public:
    AdapterInterface(int d, double r) : LegacyInterface(_w, _h)
    {
        std::cout << "AdapterInterface ctr" << std::endl;
        std::cout << "--New Interface--" << std::endl;
        std::cout << "Diagonal : " << d;
        std::cout << "  Ratio    : " << r << std::endl;
        diagToRectConverter( d,  r);
    }

    void diagToRectConverter(int d, double r)
    {
        // Calculate the square of the diagonal
        double D_squared = double(d * d);

        // Calculate the width and height
        _w= std::sqrt(D_squared / (1 + r * r));
        _h = r * _w;
    }

    void draw() override
    {
        LegacyInterface::oldDraw();
    }

private:
    double _w;
    double _h;
};

int main()
{
    int d;
    double r = 1.7778;
    std::cout << "Enter Diagonal: ";
    std::cin >> d;
    NewInterface *adapter = new AdapterInterface(d, r);
    adapter->draw();

    return 0;
}

I'd like to find an alternative approach that avoids calling diagToRectConverter twice in the constructor initialization of LegacyInterface within AdapterInterface for the given d and r values.

AdapterInterface(int d, double r) : LegacyInterface(std::get<0>(diagToRectConverter(d, r)), std::get<1>(diagToRectConverter(d, r)))

Aucun commentaire:

Enregistrer un commentaire