Saturday, December 29, 2012

C++ Explicit Constructors

The new EditBox class was created using QtCreator's new class wizard and I noticed that it put the explicit keyword in front of the constructor definition (it also did this with the MainWindow class).  (More about the new EditBox class in the post.)  Curious what this keyword does (which was added since I learned C++ in the early 90's), I did some research.  The explicit keyword tells the compiler not to allow implicit type conversions on constructors that take a single argument.  Consider this partial example:
class MyFloat {
    float m_value;
public:
    MyFloat(int value): m_value(value) {}
    float value(void) { return m_value; }
};

float square(MyFloat myFloat) {
    return myFloat.value() * myFloat.value();
}

MyFloat something = 47;
std::cout << square(12) << std::endl;
On the last two lines, implicit conversions occur from int to MyFloat, which are perfectly acceptable  for this simple class.  However, if the implicit conversion was not desired, the explicit keyword can be added in front of the constructor to prevent it.  The compiler will now generate errors for the last two lines above.  These lines can be rewritten to work:
MyFloat something = MyFloat(47);
std::cout << square(MyFloat(12)) << std::endl;
This is a contrived example and would probably make sense to allow the implicit conversion in this class, however, this is not the case with the classes used in this project.  Therefore, the explicit keyword was added to all the constructors that take a single argument, which included the CommandLine, Parser, Tester, Token and Translator classes.

The most glaring constructor requiring explicit was the Token constructor Token(int column = -1) that would have allowed a statement like Token token = 47;, which does not make sense (a token should not be assigned an integer).

[commit 5979939788]

No comments:

Post a Comment

All comments and feedback welcomed, whether positive or negative.
(Anonymous comments are allowed, but comments with URL links or unrelated comments will be removed.)