C++ Assignment Operator as the Delphi Implicit Operator

From RAD Studio
Jump to: navigation, search

Go Up to Support for Object Pascal Data Types and Language Concepts


This section describes the C++Builder syntax for using the C++ assignment operator as the Delphi implicit operator.

In Delphi, the implicit operator is used for both assignment and construction. In C++ for C++Builder, it is possible to use the operator= only for assignment to the result type; but not for constructing the result type.

This syntax allows using the operator= for assignment in C++, the same as the implicit operator is used in the Delphi side.

A clear case that illustrates this is for example when using TValue in C++, where you have several implicit operators in Delphi that allow users to assign several types transparently.

Delphi:

procedure doSomething();
var
  a : TValue;
begin
  a := 'assigning a string';
  a := 123;
  a := 3.14;
end;

Without the assignment operator, the C++ equivalent of the above Delphi code is the following.

C++:

void doSomethingCppOld()
{
  TValue a;
  a = TValue::_op_Implicit(UnicodeString(L"assigning a string"));
  a = TValue::_op_Implicit(123);
  a = TValue::_op_Implicit(3.14L);
}

With the assignment operator, it is possible to write the C++ equivalent like this.

C++:

void doSomethingCpp()
{
  TValue a;
  a = UnicodeString(L"assigning a string");
  a = 123;
  a = 3.14L;
}
Note: Whether you use the first or the second C++ version, it is important that you call the UnicodeString constructor when assigning a literal string, since its type is const wchar_t * (or const char *, if no L prefix is written). Otherwise, the pointer would be evaluated as a Boolean expression, because it is the best match, probably resulting in a call to an unexpected implicit operator.

See Also