HP aC++/HP C A.06.25 Programmer's Guide
Example
class C {
public:
explicit C(int);
};
C::C(int)
{
// empty definition
}
void 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
};
void 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
};
void main()
186 Standardizing Your Code