tags:

views:

118

answers:

2

Hi

i have created some application in managed c++.when i try to instantiates it shows error as

cannot convert from obj to *obj. when i instantiates as pointer obj it shows no error.

so. is there any way to access such class without creating pointer object

A: 

You could create it on the stack.

MyObject foo;
foo.bar();   // accessing bar method on object foo

Maybe the syntax you are looking for is this:

MyObject *foo = new MyObject;
foo->bar;
mikelong
+2  A: 

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.

Daniel Earwicker
can I make thisConsole.WriteLine(c.ToString()); ??
Ahmed Said
Yes, if c is an object (as in third code example). ToString() returns a handle (System.String ^) which is what WriteLine accepts. If c is a handle, you'd need to put c->ToString().
Daniel Earwicker