17

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??

learnvst
  • 15,455
  • 16
  • 74
  • 121

1 Answers1

15

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.

Pubby
  • 51,882
  • 13
  • 139
  • 180
  • "avoid delegating constructors in this example" - Seeing as your code works (thanks +1), could you expand on why you make this suggestion? – learnvst Nov 27 '12 at 18:53
  • @learnvst They are acting as a fancy default argument. I find default arguments or your original code to be more readable. – Pubby Nov 27 '12 at 18:56
  • Yeah, the `Window(Rectangle())` thing does look a bit odd. I see where you are coming from. – learnvst Nov 27 '12 at 19:01
  • 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. – Grizzly Nov 27 '12 at 20:31