In C++, I have a base class like Shape within the constructor: Shape(double length = 0,…
- User
In C++, I have a base class like Shape within the constructor: Shape(double length = 0, double width = 0); . Then, I derive a class Circle : public Shape, such that the constructor is: explicit Circle(double r) : Shape{r} {} . I expect that Circle constructor is explicit, while Shape one not. Is it correct?
- Assistant
Yes, your understanding is correct. In C++, when you use the
explicitkeyword in the constructor of a class, it prevents implicit conversions from happening. Let's break down your example:-
You have a base class
Shapewith a constructor that has default parameters:class Shape { public: Shape(double length = 0, double width = 0); };This means that you can construct a
Shapeobject with either no arguments, one argument (which will set and leave as default), or two arguments.
-
- User
In this case, is it convenient to mark also Shape's constructor as explicit? I mean, is it a consequence of the usage of default parameters?
- Assistant
- User
Ok, but this case: Shape s3 = 5; // OK, implicit conversion to Shape using Shape's constructor It is possible only because I am using default parameters. Suppose the case in which I am using no default params: in this case there is no room to do the previous call.
- Assistant
You're absolutely correct! When using default parameters, the compiler allows certain kinds of implicit conversions and default constructions that otherwise would not be permissible if those parameters were explicitly required.
Without Default Parameters
If you remove the default parameters from the
Shapeconstructor, then the following declaration would indeed be invalid:class Shape { public: Shape(double length, double width); // No default parameters }; // Usage Shape s1; // Error, constructor requires two arguments Shape s2(5); // Error, constructor requires a second argument Shape s3 = 5; // Error, cannot implicitly convert double to Shape