Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to organize initializer lists in constructors

Sometimes there is a need to do some processing on the class constructor arguments before initializing const members or those not having a default constructor.

For instance, in Java I can do this (don't ask why, it's just an example):

class A
{
    public A(int area, float aspectRatio) {
        int w = foo(area, aspectRatio);
        int h = bar(area, aspectRatio);
        image = new Image(w, h);
    }
    private final Image image;
}

In C++ the same would look like

class A
{
public:
    A(int area, float aspectRatio)
         : image(foo(area, aspectRatio), bar(area, aspectRatio))
    {
    }
private:
    const Image image;
}

And with more members needing a complex initialization the initializer list becomes more and more monstrous. Is there a way around this problem?

UPD 1:
What if the member does not have a copy constructor? Just extract computations for each argument to a function as in the example?

like image 495
Alex Avatar asked Nov 27 '25 03:11

Alex


1 Answers

Write a static member function for it:

class A
{
public:
    A(int area, float aspectRatio)
         : image(initImage(area, aspectRatio))
    {
    }
private:
    const Image image;
    static Image initImage(int area, float aspectRatio) {
        int w = foo(area, aspectRatio);
        int h = bar(area, aspectRatio);
        return Image(w, h);
    }
};
like image 51
songyuanyao Avatar answered Nov 28 '25 15:11

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!