Saturday, July 30, 2011

A Reminder About Implicit Conversion and Default Value Arguments

Implicit conversion is usually undesirable, and as a general rule, single-parameter constructors should be explicit unless there is a specific reason otherwise. Using the explicit keyword, we declare a constructor to be non-converting:
class Stuff
{
public:
    explicit Stuff(int n)
    {
    }

    // ...
}

Stuff stuff = 5;            
// error: conversion from ‘int’ to non-scalar type ‘Stuff’ requested

Stuff stuff(5);             // ok
But what if the constructor takes more than one argument, and default values are specified for the additional, or for all arguments? We can still call this constructor using one parameter only. Consider the following example:
class Stuff
{
public:
    Stuff(int x, int y = 0, int z = 1)
    {
    }

    // ....
}

Stuff stuff = 5;            // aargh!
The explicit keyword should be used here as well. So, the rule actually applies to:
  • single argument constructors, and
  • multiple argument constructors, if all OR all except one of the arguments have a default value.

0 comments:

Post a Comment