3

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?

Alex
  • 1,165
  • 2
  • 9
  • 27

2 Answers2

4

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);
    }
};
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
3

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;
}
Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416