Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 207
learnvst Avatar asked Nov 27 '12 18:11

learnvst


People also ask

What is a delegating constructor?

Delegating constructors. Constructors are allowed to call other constructors from the same class. This process is called delegating constructors (or constructor chaining). To have one constructor call another, simply call the constructor in the member initializer list.

What are delegating constructors in C++?

Delegating constructors can call the target constructor to do the initialization. A delegating constructor can also be used as the target constructor of one or more delegating constructors. You can use this feature to make programs more readable and maintainable.

Can you create a delegate to a constructor in C#?

Can you create a delegate to a constructor in C#? No. No, constructors are not quite the same things as methods and as such you cannot create a delegate that points to them.

Does default constructor initialize members?

Implicitly defined (by the compiler) default constructor of a class does not initialize members of built-in types.


1 Answers

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.

like image 61
Pubby Avatar answered Sep 16 '22 22:09

Pubby