The question says you're using Managed C++, and the tags say you're using C++/CLI (available in VS 2005 or later). You'll probably have a less confusing time with C++/CLI.
If that's what you're using, then there are two ways to "translate" from C#. Suppose you have some C#:
// Construct
MyClass c = new MyClass();
// Call some method
c.MyMethod();
Console.Writeline(c); // will call ToString on MyClass
// Finished with it
c.Dispose();
You can write this in C++/CLI like this:
MyClass ^c = gcnew MyClass;
// Call some method
c->MyMethod();
Console.Writeline(c); // will call ToString on MyClass
// Finished with it
c->Dispose();
The variable c
is called a "handle", not a pointer, declared with ^ instead of *. Also we have to use gcnew
instead of new
. This is the same thing as a reference variable in C#, and is analogous (but not identical) to a pointer in C++, so we use ->
to access members.
Or you can write it like this:
// Create with local scope
MyClass c;
// Call some method
c.MyMethod();
Console.Writeline(%c); // will call ToString on MyClass (note the %)
First thing to note: we declare it in the style of a local C++ variable. There is no need to explicitly gcnew
the object. Secondly, we treat the object as if it was a local variable (or a C++ reference to such a variable). So we use . instead of ->
. Thirdly, we can "convert" this local object into a handle, by prefixing it with %
, which acts like the .NET equivalent of &
that we use with ordinary pointers. It means "take the address of" or "give me a handle to" an object. Finally, we don't have to call Dispose
on the object. The compiler does that for us at the end of the scope in which we declared it, as the Dispose
method is the mechanism by which destructors are implemented in C++/CLI.