What does the explicit keyword mean in C++? When and why should it be used?
Hi everyone! I just started learning C++ and came across the `explicit` keyword. I understand that it is used before constructors, but I don't fully understand why it is needed and in what cases to use it.
I have a simple class for working with a vector:
```cpp
class Vector {
public:
Vector(int size) {
data = new int[size];
sz = size;
}
private:
int* data;
int sz;
};
```
I can write code like this:
```cpp
Vector v = 10; // Why does this work?!
```
The compiler compiles this without errors. But isn't `10` a number? Why does it suddenly turn into a Vector object? Is this some kind of implicit conversion? This seems dangerous to me, because I could accidentally pass a number where an object is expected, and the program will behave strangely.
No answers yet.
Log in to leave an answer