views:

300

answers:

1

I am using a C++ language I am getting a strange error when I am try to create a simple object of DataTable its giving error

System::Data::DataTable* myDataTable = new DataTable();

even I tried this System::Data::DataTable myDataTable = new DataTable(); getting the following error please help.

error C2750: 'System::Data::DataTable' : cannot use 'new' on the reference type; use 'gcnew' instead error C2440: 'initializing' : cannot convert from 'System::Data::DataTable *' to 'System::Data::DataTable ^

+9  A: 

The language you are using is called C++/CLI, not plain C++. In C++/CLI, you can access .NET stuff like DataTable. The semantics are a bit different from raw pointers:

DataTable^ myDataTable = gcnew DataTable;

"^" denotes a managed handle. Under the hood, it's a pointer to an object on the GC heap. You can't do pointer arithmetic on managed handles. You don't delete them manually. The GC will take care of them. It's also free to move the objects around unless they are pinned explicitly. gcnew is used to allocate objects on the managed heap. It returns a handle, not a raw pointer. You can't create .NET reference types on unmanaged C++ heap using new.

Mehrdad Afshari
Impressive Mehrdad, It solved my problem. Thanks very much :)
Sachin
+1 Very succinct!
Andrew Hare

related questions