explicit

From RAD Studio
Jump to: navigation, search

Go Up to Keywords, Alphabetical Listing Index


Category

C++ Specific Keywords

Syntax

explicit <single-parameter constructor declaration>

Description

Normally, a class with a single-parameter constructor can be assigned a value that matches the constructor type. This value is automatically (implicitly) converted into an object of the class type to which it is being assigned. You can prevent this kind of implicit conversion from occurring by declaring the constructor of the class with the explicit keyword. Then all objects of that class must be assigned values that are of the class type; all other assignments result in a compiler error.

Objects of the following class can be assigned values that match the constructor type or the class type:

class X {
public:
X(int);
X(const char*, int = 0);
};

Then, the following assignment statements are legal.

void f(X arg) {
X a = 1;
X B = "Jessie";
a = 2;
}

However, objects of the following class can be assigned values that match the class type only:

class X {
public:
explicit X(int);
explicit X(const char*, int = 0);
};

The explicit constructors then require the values in the following assignment statements to be converted to the class type to which they are being assigned.

void f(X arg) {
X a = X(1);
X b = X("Jessie",0);
a = X(2);
}

See also