Canvas FillText non-const compiler error

403 Views Asked by At

In BDS XE6 I am trying yo put text using Canvas->FillText. I have some issues with const declaration and am not able to overcome the problem.

TRect *Rect = new TRect(0, 0, 100, 30);
Canvas->FillText(*Rect, "Hello", false, 100, TFillTextFlags() << TFillTextFlag::RightToLeft, TTextAlign::Center, TTextAlign::Center);

I get the compiler error:

[bcc32 Error] MyForm.cpp(109): E2522 Non-const function _fastcall TCanvas::FillText(const TRectF &,const UnicodeString,const bool, const float,const TFillTextFlags,const TTextAlign,const TTextAlign) called for const object
  Full parser context
    LavEsiti.cpp(107): parsing: void _fastcall TMyForm::MyGridDrawColumnCell(TObject *,const TCanvas *,const TColumn *,const TRectF &,const int,const TValue &,const TGridDrawStates)

I'd like to get some info on my mistake. Thank's in advance.

2

There are 2 best solutions below

0
On

Problem solved by calling function with const_cast option:

const_cast<TCanvas*>(Canvas)->FillText(*Rect, "Hello", false, 100, TFillTextFlags() << TFillTextFlag::RightToLeft, TTextAlign::Center, TTextAlign::Center);
0
On

TRect *Rect = new TRect(0, 0, 100, 30);

You do not need to dynamically allocate the TRect, use a stack-based instance instead:

TRect Rect(0, 0, 100, 30);
Canvas->FillText(Rect, ...);

Or, use the Rect() function without a variable at all:

Canvas->FillText(Rect(0, 0, 100, 30), ...);

I get the compiler error: [bcc32 Error] MyForm.cpp(109): E2522 Non-const function _fastcall TCanvas::FillText(const TRectF &,const UnicodeString,const bool, const float,const TFillTextFlags,const TTextAlign,const TTextAlign) called for const object

Delphi (which the VCL is written in) has no concept of const-ness for class methods, like C++ does. The Canvas parameter of the OnDrawColumnCell event is declared as const (I do not know why), but the TCanvas::FillText() method is not declared as const. That is why you get the Non-const function ... called for const object error. Delphi has no problem with that, but C++ does.

As you already discovered, you can const_cast the error away, but that is more of a hack than a solution. The event handler should not be declaring an object pointer as const to begin with, that is an oversight on whoever wrote that event in the first place.