An important difference, which no one seems to have mentioned yet, is this:
Myclass mc = new Myclass();
in C#, this is the only correct way to create a new object. When you need an object, this is how you create it.
MyCppClass *mcCppClass = new MyCppClass();
In C++, this is how you can create an object, and how you occasionally have to create an object. The problem with using this approach in C++ is that:
new
is extremely slow in C/C++, compared to a managed language. If used to allocate every object you need, it's going to hurt.
- The object has no fixed lifetime. It is allocated on the heap, and it is not destroyed until you call
delete
on it. If you forget to do so, it is never destroyed. If you call delete
twice, your program blows up.
In C++, you have two ways to create objects:
The one you used above:
// 1
MyCppClass *myobject = new MyCppClass();
delete myobject;
but modified to include the delete
call as well, because without it, you're leaking memory. Whenever you use new
, you must also, sooner or later, call delete
. One without the other is, in general, an error.
And the second, more common, approach:
// 2
MyCppClass myobject;
The second one is, in some ways, more similar to your C# example. Its lifetime is automatically managed by the system (although the way it is managed is different. In C++, it lasts until it goes out of scope, where in C# it lasts until no one references it and it gets garbage collected - but in both cases, you don't have to do anything to ensure it is destroyed). It is also, in general, the correct way to create object instances, for the same reason.
One of the most common mistakes made by new C++ programmers is to use new
to allocate every object, store pointers to them, and then try to remember to delete them. A simpler, more robust and more efficent solution is to avoid new
and avoid pointers as far as possible. Occasionally, you need an object whose lifetime is not limited to the declaring scope, (and where copying the object isn't an option for using it outside that scope). Then you use new
, and most likely, wrap the resulting pointer in a smart pointer of some type.