C++ has a feature (I cannot figure out the proper name of it), that automatically calls matching constructors of parameter types if the argument types are not the expected ones.
A very basic example of this is calling a function that expects a std::string
with a const char*
argument. The compiler will automatically generate code to invoke the appropriate std::string
constructor.
I'm wondering, is it as bad for readability as I think it is?
Here's an example:
class Texture {
public:
Texture(const std::string& imageFile);
};
class Renderer {
public:
void Draw(const Texture& texture);
};
Renderer renderer;
std::string path = "foo.png";
renderer.Draw(path);
Is that just fine? Or does it go too far? If I shouldn't do it, can I somehow make Clang or GCC warn about it?
Best Answer
This is referred to as a converting constructor (or sometimes implicit constructor or implicit conversion).
I'm not aware of a compile-time switch to warn when this occurs, but it's very easy to prevent; just use the
explicit
keyword.As to whether or not converting constructors are a good idea: It depends.
Circumstances in which implicit conversion makes sense:
std::string
reflecting the same concept as theconst char *
it can implicitly convert from), so implicit conversion makes sense.Circumstances in which implicit conversion makes less sense:
AnsiString
class should not implicitly construct from aUnicodeString
, since the Unicode-to-ANSI conversion may lose information.Further reading: