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 Conversion Constructor Reviewed by Sourabh Soni on Friday, February 12, 2010 Rating: 5

No comments

Author Details

Image Link [https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgZYEKEHJPev0oC4dyp_vZFA3Q6PM99sbRGRgel5lr3s9PJPKQORaMDhc5f0wLqZjHSE79OnUom2STt1asn17AKrN2FPD6gH6gjz4sCmL-fCfCp5ksFbAT6sqxx02KLzi2C_Q2kSMTtQhIM/s1600/sourabhdots3.jpg] Author Name [Sourabh Soni] Author Description [Technocrat, Problem Solver, Corporate Entrepreneur, Adventure Enthusiast] Facebook Username [sourabh.soni.587] Twitter Username [sourabhs271] GPlus Username [#] Pinterest Username [#] Instagram Username [#] LinkedIn Username [sonisourabh] Youtube Username [sonisourabh] NatGeo Username [271730]