Better way to organize initializer lists in constructors

Sometimes it becomes necessary to do some processing on class constructor arguments before initializing members const

or those that do not have a default constructor.

For example, in Java I can do this (don't ask why, this is 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 a lot of members needing complex initialization, the initializer list is getting more and more monstrous. Is there a way to solve this problem?

UPD 1:
What if the user doesn't have a copy constructor? Just extract the computation for each function argument like in the example?

+3


source to share


2 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);
    }
};

      

+4


source


Extract to function.



Image initImage(int area, float aspectRatio)
{
    return {foo(area, aspectRatio), bar(area, aspectRatio)};
}

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

      

+3


source







All Articles