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

learnvst picture learnvst · Nov 27, 2012 · Viewed 7.3k times · Source

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

Answer

Pubby picture Pubby · Nov 27, 2012

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.