Alex
Alex

Reputation: 1175

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?

Upvotes: 3

Views: 137

Answers (2)

songyuanyao
songyuanyao

Reputation: 172894

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

Upvotes: 4

Vittorio Romeo
Vittorio Romeo

Reputation: 93264

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

Upvotes: 3

Related Questions