S
S
sabn1k2016-02-22 09:11:05
C++ / C#
sabn1k, 2016-02-22 09:11:05

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

2 answer(s)
A
Alexander Taratin, 2016-02-22
@sabn1k

Why can't we just remove it and initialize the object implicitly?

Explicit is better than implicit.
I took for myself the rule to mark all constructors as explicit. I don't know the negative effects, but not shooting off the leg in the future will help a little.

A
Alexander Movchan, 2016-02-22
@Alexander1705

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 explicitif 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 question

Ask a Question

731 491 924 answers to any question