explicit keyword

Started by
1 comment, last by _goat 16 years, 8 months ago
I've read about it and I still don't understand what it does and why it's necessary. Could someone be so kind as to help my understanding? Thank you.

Beginner in Game Development?  Read here. And read here.

 

Advertisement
Consider a constructor with one argument:

class Foo{
public:
Foo(int a);
};

You can instantiate it one of two ways (excluding the case involving the default copy constructor).

Foo f1(5);

OR

Foo f1 = 5;

Quote:
ASIDE: Note that the second example uses the single argument constructor and not the '=' operator. For your reference, the following example would use the '=' operator.

Foo f1;
f1 = 5; // Here we would have had to have defined '=' in our class



Back to your question ... If we do not want the implicit conversion from int to Foo that occurs in second example, we classify the constructor as explicit.

This will render the following line invalid:

Foo f1 = 5;

[edit]

As for the reason why you would use an explicit constructor? Basically any time you don't want an implicit conversion to occur. For example:

void processFoo(Foo f){
...
}

Foo f(4);
processFoo(f); // This line is valid
processFoo(5); // This line is also valid.

In the second line our constructor performed the implicit conversation from int to Foo, which may be unwanted.

[Edited by - fpsgamer on August 5, 2007 12:10:43 AM]
Quote:Original post by fpsgamer
void processFoo(Foo f){
...
}

Foo f(4);
processFoo(f); // This line is valid
processFoo(5); // This line is also valid.

In the second line our constructor performed the implicit conversation from int to Foo, which may be unwanted.


The boost::shared_ptr uses an explicit constructor for that very reason.
[ search: google ][ programming: msdn | boost | opengl ][ languages: nihongo ]

This topic is closed to new replies.

Advertisement