What does the explicit keyword mean in C++ and why is it needed?
Hello everyone! I started learning C++ and came across the `explicit` keyword before constructors. So far I understand that it has something to do with implicit conversions, but I don't fully grasp why it should be used.\n\nHere's a simple example I wrote. I have a class `String` that takes a number (string size) in its constructor:\n\n```cpp\nclass String {\npublic:\n String(int size) {\n // some code\n }\n};\n\nvoid printString(const String& s) {\n // print the string\n}\n\nint main() {\n printString(42); // This works! But why?\n return 0;\n}\n```\n\nI'm passing the number `42` to the `printString` function, even though it expects a `String` object. And this compiles! It seems strange to me and could lead to errors. For example, if I accidentally pass the wrong type, the compiler
No answers yet.
Log in to leave an answer