Boris
Boris

Reputation: 1467

Calling a property on the const reference

I have C++/CLI class that defines a property:

public ref class AbstractOffer 
{
  public:
    AbstractOffer();

    property String^ Body;
};

In some function the AbstractOffer class is passed by const ref

foo(const AbstractOffer^ ao)
{
  ao->Body;
}

When I call the property the method compiler gives the following error :-

error C2662: 'ivrworx::interop::AbstractOffer::Body::get' : cannot convert 'this' pointer from 'const ivrworx::interop::AbstractOffer' to 'ivrworx::interop::AbstractOffer %' 1> Conversion loses qualifiers

It seems somehow connected to const. How can I call the Body property of the object if the object reference is passed by const?

Upvotes: 1

Views: 395

Answers (2)

Hans Passant
Hans Passant

Reputation: 941635

The const qualifier is a problem in C++/CLI. It is only meaningful when it can be checked and that's not in general possible in .NET. It is of course not a problem when you only have one kind of compiler and that compiler follows strict language rules. Like C++. But .NET supports many languages, your method could be easily called from a Cobol.NET program for example. The odds of ever getting const-correctness added to the Cobol language are zero.

The compiler does compile code with const qualifiers and does make an effort to check when it can. Which is why you got the diagnostic. That can even work when the declaration exists in another assembly, as long as it was compiled with C++/CLI, the compiler emits modopt annotations in the metadata.

But there are limitations with that. Properties are one of them, you can't add the const qualifier to the getter, or a member function in general, you'll get slapped with C3842.

Best thing to do is to use C++/CLI for what it is good at, it is an interop language. And const qualifiers just don't work well in an interop scenario.

Upvotes: 3

Grhm
Grhm

Reputation: 6834

The only way I know to get round this is the cast away the const-ness. As long as you don't modify the object, it should be fine. (If you do modify it, I've no idea what the outcome will be).
i.e. change your function to be

void foo(const AbstractOffer^ ao)
{
  const_cast<AbstractOffer^>(ao)->Body;
}

Upvotes: 0

Related Questions