Marking constructors as explicit

In some cases, you do not want to allow the implicit conversion between one type that is passed as a parameter of the constructor of another type. To do this, you need to mark the constructor with the explicit specifier. This now means that the only way to call the constructor is using the parentheses syntax: explicitly calling the constructor. In the following code, you cannot implicitly convert a double to an object of mytype:

    class mytype  
{
public:
explicit mytype(double x);
};

Now you have to explicitly call the constructor if you want to create an object with a double parameter:

    mytype t1 = 10.0; // will not compile, cannot convert 
mytype t2(10.0); // OK
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset