Explicit Conversion Operators (C++11)

From RAD Studio
Jump to: navigation, search

Go Up to C++11 Features in the Classic Compiler

Attention: This page refers to a C++11 feature in the Classic compiler. The Classic compiler is not recommended: instead it is recommend you use the Clang-enhanced compilers, which support modern C++ including C++11, C++14 and C++17.

BCC32 includes support for explicit conversion operators, one of the features in the C++11 standard.

You can now apply the function specifier explicit in the definition of a user-defined conversion operator. Previously, explicit constructors (including copy constructors) were added to the language in order to prevent unintended conversions being implicitly called by the compiler. Now explicit conversion operators have been added to provide the same control over unintended conversion calls.

Conversion functions declared as explicit work in the same contexts as explicit constructors (that is, direct-initialization, explicit type conversion). Explicit conversion operators produce compiler diagnostics in the same contexts (copy-initialization) as explicit constructors do.

For example:

class T {
};

class X {
public:
    explicit operator T() const ;
};

void m() {
    X x;

    // with cast
    T tc = (T)x; // ok

    // without cast
    T t = x; // error: E2034 Cannot convert 'X' to 'T'
}

See Also