That depends on what you mean by "same result". There isn't much functional difference in this code given they both occur in
main.
new returns a pointer or address to a newly created object with dynamic storage duration. Line 5 creates such an object via
new and assigns the resulting address to the pointer
myCar.
myCar itself has automatic storage duration.
Line 12 creates a
Car object with automatic storage duration.
Line 13 creates a
pointer-to-Car with automatic storage duration and assigns to it the address of
fredsCar.
The first method would normally require the use of
delete, but that it isn't strictly necessary if you're not worried about leaking memory (and you can arguably not be worried about it in
main.)
Also, In the first method what does the "new" keyword do in relation to creating an object pointer? |
In a sense new does create a pointer, but its purpose is to create an object and return the address of the newly created object. On line 5,
new has nothing to do with the creation of
myCar.
myCar is simply initialized with the value the
new expression results in.