Archived

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

dave

What is an Implicit Conversion?

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...

public:
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;
public:
explicit MySmartPtr(T*);
};


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

Regards,
Jeff


[ CodeDread ]

Share this post


Link to post
Share on other sites