C++ Programming: Implicit and Explicit Constructors
Ashish Bailkeri
Posted on October 18, 2021
Note: Any code snippets posted here are licensed under the MIT License.
Did you know that there are both implicit and explicit constructors?
Let's look into the difference between both, and what each can do for code readability and convivence when programming.
Explicit Constructors
You may see warnings in certain C++ compilers about making certain constructors explicit. But what does it mean? Let's look at an example of an explicit constructor:
class MyClass {
int i;
explicit MyClass(int i) : i(i) {}
}
// ...
int main() {
MyClass clz = MyClass(2);
}
Looks pretty normal, right? So you might wonder what this actually does. You must initialize the value with the name of the type before it's initialization aka: MyClass
then with the constructor parameters. You can see the difference in usability in the implicit constructor code.
Implicit Constructors
These constructors allow you to initialize a class value without specifying the name of the class. Let's look at an example:
class MyClass {
int i;
/*implicit*/ MyClass(int i) : i(i) {}
}
// ...
int main() {
MyClass clz = 2;
}
Wait, is the class MyClass
now the integer type? No. What actually happened was that the C++ compiler was able to tell that you were calling the MyClass
constructor implicitly and allowed that conversion.
Every wondered why this code was legal?
std::string my_string = "Wow, this is cool!";
It's because there is an implicit constructor with std::string that takes in a const char *
and thus allows this initialization to be valid.
Bringing It Together
In accordance with certain code writing standards, compilers or code analyzers may warn using implicit constructors, why? They do this because in general it is harder for another programmer to analyze code that uses implicit constructors because it is hard to pin point the type of the object being initialized.
Conclusion
Understanding implicit and explicit constructors will allow you to take in full control of how your code is read and how you use it. This is especially important to take note of if you are reviewing code, or reading code from a library. I hope you learned something today, and have good day!
Posted on October 18, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.