1

I have a old c++ code, wirited and compiled into c++ builder 5. But now, I need to update/migrate this code to c++ builder 2009. So, I have some problems:

int __fastcall TAllConversor::ListToStr(
    const TStringList* pList,
    AnsiString& strValue,
    const long lngLimiteInferior,
    const long lngLimiteSuperior) const
{
  long lngIndice;
  AnsiString strAux;

  try
  {
    if (lngLimiteSuperior == 0)
      lngIndice = pList->Count;
    else
      lngIndice = lngLimiteSuperior + lngLimiteInferior;

    for (int i = lngLimiteInferior; i < lngIndice; i++)
    {
      strAux += pList->Strings[i] + ";";
    }

    strValue = strAux;
    return 1;
  }
  catch(...)
  {
    return 0;
  }
}

At line "lngIndice = pList->Count;" I get this error: "E2522 Non-const function _fastcall TStrings::GetCount() called for const object".

So, how can I solve (work around) it?

3
  • 1
    In this code, I have not seen anything about "TStrings::GetCount()" ? Where did you called ? From error, I understand declaration and definition of function is not match or function is called with const object but you should not do. Answer : use Casting Commented Jul 12, 2012 at 13:55
  • We need to see some info about TStringList as that is probably incorrect and that is the code change to make Commented Jul 12, 2012 at 13:58
  • 1
    @gcc: TStringList is a VCL class. Its Count property calls the GetCount() method. Commented Jul 12, 2012 at 22:42

1 Answer 1

3

Would help if you provided an exact definition of TStringList but I'll just assume it's a templatized array for the typename TString.

Work-around could be to cast away the const, as in:

lngIndice = (const_cast<TStringList*>(pList))->Count;

Of course it's just what it is - a work-around and you may want to look at providing a const-correct access function in TString itself instead

Sign up to request clarification or add additional context in comments.

2 Comments

you assume incorrectly about what TStringList is. It is not a templated class. It is a Borland VCL class written in Delphi. But your solution is still valid. The GetCount() method is not declared as const (and that cannot be changed), so the pList parameter needs to have its constness removed to avoid the compiler error, either via const_cast or by simply removing the const from the pList parameter (Delphi is not as const-correct as C++ can be).
you are going to have the same problem accessing the pList->Strings[] property - it calls the TStrings::Get() method, which is not declared as const either, so you will have to remove the constness on that call as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.