0

I already have found useful answers why it shouldn't be possible at all:
Why does C# limit the set of types that can be declared as const?
Why can't structs be declared as const?
The first one has a detailed answer, which I still have to re-read a couple of times until I fully get it.
The second one has a very easy and clear answer (like 'the constructor might do anything, so it had to be run and evaluated at compile time').
But both refer to C#.

However, I am using C++/CLI and have a

value class CLocation
{
public:
  double x, y, z;

  CLocation ( double i_x, double i_y, double i_z) : x(i_x), y(i_y), z(i_z) {}
  CLocation ( double i_all) : x(i_all), y(i_all), z(i_all) {}

  ...
}

where I can easily create a

const CLoc c_loc (1,2,3);

which indeed is immutable, meaning 'const'.

Why?

CLocation furthermore has a function

System::Drawing::Point CLocation::ToPoint ()
{
  return System::Drawing::Point (x_int, y_int);
}

which works well on CLocation, but doesn't on a const CLocation. I think this comes from the limitation in C# (known from the links above), which likely comes from the underlying IL, so C++/CLI is affected by that limitation in the same way.

Is this correct?
Is there a way to run this member function on a const CLocation?

Community
  • 1
  • 1
Tobias Knauss
  • 3,361
  • 1
  • 21
  • 45
  • The ToPoint() function is a const violation, it is not a const function. C++/CLI supports const when it can, it is imperfect because .NET metadata does not allow expressing it everywhere it is valid in C++. Like on a function, the [modopt] it has to use is not valid on methods. Use `initonly` instead. – Hans Passant Sep 18 '16 at 19:14

1 Answers1

0

You must indicate to the compiler that your function doesn't change the object by adding const after the argument list.

Your function may then be called on a const variable, but may not modify its fields.

Pay also attention that some keywords (including const and struct) have different meanings in C# and C++ (and other languages based on C).

Update

As CPP/CLI doesn't allow a const modifier on a member function, you'll have to copy the variable to a non-const one to be able to call any member function (on the copy).

Philippe
  • 1,225
  • 7
  • 9
  • tried that already. declaring `System::Drawing::Point ToPoint () const;` produces: error C3842: 'ToPoint': Die Qualifizierer 'const' und 'volatile' für Memberfunktionen von verwalteten Typen werden nicht unterstützt. (englisch original message from MSDN: 'function': 'const' and 'volatile' qualifiers on member functions of WinRT or managed types are not supported) – Tobias Knauss Sep 18 '16 at 18:36