const-correctness

Top  Previous  Next

What is partially translated > const-correctness

 

Compared with the concept the const-correctness in C++ the use of const in Delphi is very limited. In the Delphi const-section true constants are declared whose values cannot change and the keyword const also can be used to declare constant parameters. No values can be assigned to constant parameters and they cannot be passed to routines, where var parameters are expected. But unlike C++, Delphi does not permit methods to be marked as const. The VCL pendant of the C++Builder is not designed for C++ const-correctness.

 

If the translated Delphi code simply should compile, it would be the best to ignore the const-qualifier totally. But it is the aim of Delphi2Cpp II, that the created C++ code should be C++-like code and the translation also is orientated at the way the C++Builder produces  C++-header files from Delphi sources. C++Builder leaves the const qualifiers for parameters. For example:

 

 

TMyClass = class

private

  FObject : TObject;

public

  constructor Create(const Obj: TObject);

 

The declaration of a constructor is translated by C++Builder and accordingly by Delphi2Cpp II to

 

__fastcall TMyClass( const TObject* Obj );

 

 

But this leads to a problem in the body of the constructor, where the parameter is assigned to a member of the class:

 

 

__fastcall TMyClass::TMyClass( const TObject* Obj )

 : FObject(Obj)

{

}

 

Compiling this code produces the error: E2034 conversion of 'const TObject *' to 'TObject *' not possible. So a cast is necessary, which strips the const qualifier away:

 

__fastcall TMyClass::TMyClass( const TObject* Obj )

 : FObject((TObject*)Obj)

{

}

 

or more precisely:

 

__fastcall TMyClass::TMyClass( const TObject* Obj )

 : FObject(const_cast<TObject*>(Obj))

{

}

 

This example suggests to leave out the const-qualifier at the translation anyway as mentioned above. You can correct the code in this way, but there  are other cases where the const-qualifier should be preserved.

 

For other compilers than C++Builder the methods, which are created for the read-specifiers of properties are made const-methods.

 

 

 

 

 



This page belongs to the DelphiXE2Cpp11 Documentation

DelphiXE2Cpp11 home  Content