Jump to content
  • Advertisement


This topic is now archived and is closed to further replies.


What is an Implicit Conversion?

This topic is 5176 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

Reading about smart pointers and it constantly mentions that the explicit keyword prevents. Prevents what? regards ace

Share this post

Link to post
Share on other sites
When designing classes, if you have a constructor that accepts an argument of a particular type, the compiler will interpret that as a means of casting the indicated type to an instance of your new type. An example will help:

class MyHugeInt {
// some implementation here...

MyHugeInt(); // default constructor

MyHugeInt(const MyHugeInt& o); // copy constructor

MyHugeInt(int v); // ***


*** The constructor listed here is interpreted by the compiler as a means of casting an int to a MyHugeInt. This will happen automatically, even if it''s not something you (as the writer of MyHugeInt) intends. Thus, the following code will compile:

MyHugeInt i = 5;

The 5 is converted into a temporary MyHugeInt object, and then the copy constructor is called.

The "explicit" keyword prevents such casting from happening if it''s not something you want.

With smart pointers, an explicit keyword on a constructor like:

template<typename T>
class MySmartPtr {
T* ptr;
explicit MySmartPtr(T*);

the intention is usually to prevent a value of T* to be cast up to a smart pointer object.


[ CodeDread ]

Share this post

Link to post
Share on other sites

  • 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!