I'm confused by the two different ways and I find both of them are Okay in VS.Can u let me know the nature of the difference?
-
What is the type of `A` ? – Basile Starynkevitch Mar 09 '14 at 09:11
-
3first is a function, second is a class constructor – mangusta Mar 09 '14 at 09:11
-
@mangusta The first one is definitely not a function. – juanchopanza Mar 09 '14 at 09:18
-
@juanchopanza yes, if `Obj` is a class name. he did not specify that – mangusta Mar 09 '14 at 09:30
-
@mangusta Seriously, no. Function declarations do not have `=` in the middile. – juanchopanza Mar 09 '14 at 09:30
-
1@juanchopanza nobody talks about function declaration here. i meant function invokation, not declaration – mangusta Mar 09 '14 at 09:32
-
@mangusta In that case, both are "functions", by your strange definition of "being a function". – juanchopanza Mar 09 '14 at 09:38
2 Answers
The first one creates a default-constructed temporary object, and uses the the copy-constructor (if the assignment is in the declaration of A
) or the copy-assignment operator to copy from the temporary object to A
. Then the temporary object is destroyed.
The second creates a default-constructed object on the heap, and returns a pointer to this new object. You must later delete
this object or you will have a memory leak.

- 400,186
- 35
- 402
- 621
At this level of understanding, the best advice I can give you is to stay away from new
. You will need it later, for more complex tasks, but don't let the fact that, for instance, Java has a new
as well fool you. In C++, new
opens a whole world of issues which don't exist in other languages. One could argue that it's unfortunate that the keyword is identical in different languages... :)
To be more precise, new
in C++ means, among other things, that you create an object which will not be automatically removed from memory when you don't need it anymore. You must remember its location in memory via a pointer, and a pointer is a dangerous tool easy to abuse especially for unexperienced programmers.
void f()
{
Obj *a = new Obj();
// no automatic destruction, the object remains in memory!
}

- 27,051
- 3
- 32
- 62