Jump to content
  • Advertisement
Sign in to follow this  
Alpha_ProgDes

explicit keyword

This topic is 4000 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


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

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!