Instances of classes
Here's another C++ question that I'm curious about. In Java you only use the new keyword to create an instance of a class but in C++ there are a few ways. You can use
1) MyClass *c = new MyClass();
which returns a pointer to an instance of MyClass and there is
2) MyClass c;
which puts the actual instance of the class in the variable c and then there is
3) MyClass *c;
Both 1 and 3 are pointers to the class... so what's the difference. I know that since the first was created with new you have to later delete it. Why do you need to do this?
When do I use which?
It does really depend on what you want to do with the instance. If you only want to acces the memory location where an instance of the class is, then obviously you use a pointer.
The second one, is just like declaring a 'int x' for example.
Hope this helps.
Can't you do the same thing with all of them?
1 is an object created on the heap (which is pointed to by the pointer c), where it'll remain until it's explicitly deleted (unless you're using some form of smart pointer or garbage collector addon).
2 is an object created on the stack which will remain until the scope in which it was created ends.
3 is not an object, and cannot be used as one (unless it's pointed at one). It's a pointer to an object, and can be pointed at something created by either of the first two methods. However, the scoping rules still apply to what it is pointed at.
Hmmm... it looks like I should be using the second one more often instead of 1. Coming from the Java community I naturally want to use the new keyword.
Thanks for the clarification :D