User's Guide

explicit C(int);
};
C::C(int)
{
// empty definition
}
int main()
{
C c(5); // Legal
c = C(10); // Legal
// c = 15; // Produces a compile time error:
// Message: Cannot assign C with int.
// c + 20; // Produces a compile time error
}
A classic example of this problem is an array class:
class Vector {
public:
Vector(int n); // create a vector of n items
// other class details omitted
};
int main()
{
Vector operator + (Vector, Vector);
Vector v1(10), v2(10); // create two 10 element vectors
// details omitted
v1 = v2 + 5; // Legal - converts int 5 to a 5
// element vector and adds to v2.
// Not something you want to be
// legal
}
With the explicit keyword, the constructor can be made explicit and the declarations are legal,
but the addition is a compilation error:
class Vector {
public:
explicit Vector(int n); // create a vector of n items
// other class details omitted
};
int main()
{
Vector operator + (Vector, Vector);
Vector v1(10), v2(10); // create two 10 element vectors
// details omitted
// v1 = v2 + 5; // Not legal - generates compile-
// time error
// Message: Illegal typEs
// associated with operator +:
// Vector and int.
}
142 Standardizing Your Code