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??
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.
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#? No. No, constructors are not quite the same things as methods and as such you cannot create a delegate that points to them.
Implicitly defined (by the compiler) default constructor of a class does not initialize members of built-in types.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With