Do these two methods of creating an object pointer give the same result?

Hello.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{

//METHOD 1:
Car *myCar = new Car;



//METHOD 2


Car fredsCar;
Car *fredsCar2 = &fredsCar
}



Also, In the first method what does the "new" keyword do in relation to creating an object pointer?
Last edited on
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.
There isn't much functional difference in this code given they both occur in main.
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

I think the big difference between the two is that in the first example, class Car's destructor is never called and in the second example, it is. It's true that the destructor might not do a whole lot, but since this appears to be an academic exercise, I think that's the major difference.

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.




in the first example, class Car's destructor is never called and in the second example, it is.




Thanks
Topic archived. No new replies allowed.