How to correctly implement methods of a class returning "this" in Managed C++?

87 Views Asked by At

I have a class with a method which should return the object itself, like doing return this; in Java. I tried something like this:

Foo.h:

namespace Foo {

    public ref class Bar {
    public:
        Bar quux();
    }
}

Foo.cpp:

Foo::Bar Foo::Bar::quux() {
    return this;
}

The compiler complains: error C2440: 'return' : cannot convert from 'Foo:Bar ^const ' to 'Foo::Bar'

How do I get this right?

2

There are 2 best solutions below

1
On
   Bar quux();

That's pretty likely to be a typo. Hard to diagnose, the C++/CLI compiler doesn't always produce fantastic error messages. You should return a reference to the Bar object, it is a reference type whose objects are stored on the GC heap. There is no mechanism in .NET to automatically clone objects. You cannot depend on an auto-generated copy constructor, the kind you might be used to from native C++. The distinction between reference and value types in .NET is an important one, native C++ does not have that at all and treats all objects as values. Value types can be copied, reference types can not.

You can add the Bar(const Bar%) copy constructor to keep the compiler happy, it will automatically use it and stop complaining about quux(). But that's pretty unlikely to be correct if you want to return this. Very high odds that actually meant:

   Bar^ quux() { return this; }

Note the added ^ hat.

But then again, it is very odd to return this since a reference to the object is already required to call quux(). In other words, if you now use Bar^ foo = obj->quux(); then you can simply write Bar^ foo = obj; and be done with it. No real idea why you are doing this.

1
On

You should write the following way

Foo::Bar const& Foo::Bar::quux() {
    return *this;
}