Deleted functions

There is a more formal way to hide functions than using the scope. C++ will attempt to explicitly convert built-in types. For example:

    void f(int i);

You can call this with an int, or anything that can be converted to an int:

    f(1); 
f('c'),
f(1.0); // warning of conversion

In the second case, a char is an integer, so it is promoted to an int and the function is called. In the third case, the compiler will issue a warning that the conversion can cause a loss of data, but it is a warning and so the code will compile. If you want to prevent this implicit conversion you can delete the functions that you do not want callers to use. To do this, provide a prototype and use the syntax = delete:

    void f(double) = delete; 

void g()
{
f(1); // compiles
f(1.0); // C2280: attempting to reference a deleted function
}

Now, when the code attempts to call the function with a char or a double (or float, which will be implicitly converted to a double), the compiler will issue an error.

..................Content has been hidden....................

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