Sign in to follow this  
Alpha_ProgDes

explicit keyword

Recommended Posts

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]

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this