Delegating constructors: an initializer for a delegating constructor must appear alone
Asked Answered
E

1

20

I have a pair of constructors that work just fine in C++03 style. One of the constructors calls a superclass (or base class) constructor ...

class Window : public Rectangle
{
public: 
    Window() : win(new RawWindow(*this))
    {
        refresh();  
    }

    Window(Rectangle _rect) : Rectangle(_rect), win(new RawWindow(*this))
    {
        refresh();
    }
...

I am trying to figure out how to use the new C++11 delegating ctor functionality to neaten this up a little. However, the following code gives the following compiler error ...

class Window : public Rectangle
{
public: 
    Window() : win(new RawWindow(*this))
    {
        refresh();  
    }

    Window(Rectangle _rect) : Rectangle(_rect), Window(){}

"an initializer for a delegating constructor must appear alone" ...

Is there any way around this??

Epicene answered 27/11, 2012 at 18:40 Comment(0)
G
16

The problem is that Rectangle is getting initialized twice.

You could try changing which one delegates to what:

Window(Rectangle _rect) : Rectangle(_rect), win(new RawWindow(*this))
{
    refresh();  
}

Window() : Window(Rectangle()) {}

The best solution is probably to avoid delegating constructors in this example.

Gearalt answered 27/11, 2012 at 18:45 Comment(4)
"avoid delegating constructors in this example" - Seeing as your code works (thanks +1), could you expand on why you make this suggestion?Epicene
@Epicene They are acting as a fancy default argument. I find default arguments or your original code to be more readable.Gearalt
Yeah, the Window(Rectangle()) thing does look a bit odd. I see where you are coming from.Epicene
I would argue that the original code leads to code duplication, which is IMO almost universily a bad think. In this specific case default arguments would do the same job, however in the typical case where the constructor is not inline the delegating constructor would have the benefit of allowing you to change the default without recompiling everything using the class. Besides in my opionion default arguments actually reduce the readibility, since it is slightly less obvious that this is a default constructor.Overhand

© 2022 - 2024 — McMap. All rights reserved.