Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Object var and Object* var = new Object()

Tags:

c++

If I have a class named Object, what's the difference between creating an instance just like that:

Object var;

and:

Object* var = new Object();

?

like image 383
Puyover Avatar asked Nov 28 '22 01:11

Puyover


2 Answers

Here you are creating var on the stack:

Object var;

So in the above, var is the actual object.


Here you are creating var on the heap (also called dynamic allocation):

Object* var = new Object()

When creating an object on the heap you must call delete on it when you're done using it. Also var is actually a pointer which holds the memory address of an object of type Object. At the memory address exists the actual object.


For more information: See my answer here on what and where are the stack and heap.

like image 103
Brian R. Bondy Avatar answered Dec 19 '22 05:12

Brian R. Bondy


This:

Object var();

Is a function declaration. It declares a function that takes no arguments and returns an Object. What you meant was:

Object var;

which, as others noted, creates a variable with automatic storage duration (a.k.a, on the stack).

like image 45
James McNellis Avatar answered Dec 19 '22 05:12

James McNellis