Conversion Constructor
In C++, implicit conversion is a conversion of one type to another that does not require explicit typecast. The compiler uses a special function called conversion constructor to perform implicit conversions. A conversion constructor is a constructor of a class that takes single parameter and construct a new object of the class. Whenever an object of one type is used in an expression, where an object of a different type is expected, compiler automatically performs the implicit conversion by invoking the conversion constructors. Following example code shows the conversion constructors.
// Conversion constructor class MyString { private: char* m_char; public: MyString(char* str)’ }; // Conversion constructor - template template<typename T> class MyClass { private: T* m_tptr; public: template<class X> MyClass(const MyClass <X>& obj); }; |
Though conversion constructors are quite useful in implicit conversions, there may be a situation when it does not make sense to have a single-parameter constructor working as a conversion constructor. To avoid the single-parameter constructor to be treated as conversion constructor, one must declare the constructor with specifier explicit. If a constructor is marked explicit, it indicates that the constructor should not be considered for the purposes of implicit conversions.
// Constructor (not used for implicit conversion) class SomeClass { explicit SomeClass(); explicit SomeClass(int); }; |
Conversion Constructor
Reviewed by Sourabh Soni
on
Friday, February 12, 2010
Rating:
No comments