siery siery - 1 month ago 16
C++ Question

Constructor calling another constructor

I've been writing a simple display class that takes 3 parameters, a title and positions

x
and
y
. I want to make an interface that is going to let me define what parameters I want to use. For this I wrote this set of constructors:

XFrame(): mX(0), mY(0), mName("Display") {} /* Default class initialization */
XFrame(float x, float y): mX(x), mY(y) {} /* Position oriented class initialization */
XFrame(std::string name): mName(name) {} /* Name oriented calss constructor */

XFrame(std::string name, float x, float y) {
XFrame(name);
XFrame(x, y);
}


But g++ throws me an error:

In constructor ‘XFrame::XFrame(std::__cxx11::string, float, float)’:
../src/xframe.h:12:16: error: declaration of ‘XFrame name’ shadows a parameter
XFrame(name);


What does "declaration of ‘XFrame name’ shadows a parameter
XFrame(name);" mean?

Answer
XFrame(name);

This is not an invocation of a constructor, but a declaration of an object (with a redundant set of parentheses). It's the same as

XFrame name;

Such a local variable name would of course hide the constructor's parameter name, which is not allowed in C++ (in the top-level scope of a function).

And even if it was a constructor invocation, it wouldn't do what you want: it is not possible to call a constructor on an already existing object. Just like XFrame(x, y); does not call the constructor on this, but creates a temporary XFrame and immediately destroys it again.

If you want to re-use existing constructors, you can use delegation, but you have to do it the other way round:

XFrame(): XFrame("Display", 0, 0) {}
XFrame(float x, float y): XFrame("", x, y) {}
XFrame(std::string name): XFrame(name, 0, 0) {}
XFrame(std::string name, float x, float y): mName(name), mX(x), mY(y) {}
Comments