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

What is an Implicit Conversion?

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

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