Answer the question
In order to leave comments, you need to log in
What is explicit for?
I almost understood what it was for, but I still can't fully understand it. Clarify please.
Ok, explicit prohibits the implicit invocation of an object's constructor, but why do we need this? Why can't we just remove it and initialize the object implicitly?
Answer the question
In order to leave comments, you need to log in
Why can't we just remove it and initialize the object implicitly?
If you define a constructor that takes one and only one argument, that constructor will be used to implicitly cast from the argument's type to your class's type. Use explicit
if you want to change this behavior.
class Foo
{
public:
Foo(int v) : _v(v) {}
private:
int _v;
};
class Bar
{
public:
explicit Bar(int v) : _v(v) {}
private:
int _v;
};
void baz(Foo foo) {/* some code */}
void qux(Bar bar) {/* some code */}
int main()
{
Foo foo = Foo(4);
Bar bar = Bar(4);
baz(foo); // Ok.
baz(4); // Ok.
qux(bar); // Ok.
qux(4); // Fail.
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question