Search code examples
delphidelphi-xe2

Pass by reference to const in Delphi


Is there a c++ pass-by-reference-to-const Delpi equivalent in XE2? The c++ code would be:

void passByRef(const MyClass& param);

Solution

  • void passByRef(const MyClass& param);
    

    The const here says that you cannot modify the value to which the reference refers.

    Assuming that MyClass is mapped to a Delphi class there is nothing equivalent. In Delphi a class is a reference type. You can pass a const reference like this:

    procedure Foo(const param: TMyClass);
    

    This means that the function is not allowed to modify the value of param.

    param := ...; // this would result in a compilation error
    

    But the method is allowed to mutate the object to which param refers.

    param.DataMember := ...; // compiles
    param.SomeProperty := ...; // compiles
    param.MutateObject(); // compiles
    

    Delphi is simply missing this aspect of const that is available in C++.

    If you instead mapped to a record rather than a class, things would be a little different. Then you'd have:

    procedure Foo(const param: TRecord);
    

    Again you could not assign to param, but because this is a value type, you are also prevented from directly modifying any data members of param.

    param.DataMember := ...; // does not compile, for TRecord being a record
    

    But the compiler won't stop you calling methods on such a record that mutate the internal state. This is something of an oversight in my view, but hard for the language designers to avoid given the tools at their disposal. Again, the design of C++ is simply richer in this area, with more fine-grained constness specification allowed.

    For this reason I would strongly recommend that you consider not writing record types with instance methods that mutate the record's state.