Home > OS >  Difference between dynamic allocation and ordinary pointers in cpp
Difference between dynamic allocation and ordinary pointers in cpp

Time:10-23

I have a problem in following expressions:

MyClass *myObject;

MyClass *myObject = new MyClass();

What are the differences between them?

CodePudding user response:

The difference is that:

  • in MyClass *myObject;, myObject is uninitialized and thus doesn't point at anything meaningful

  • in MyClass *myObject = new MyClass();, myObject is initialized to point at the object that new creates.

CodePudding user response:

The difference is that one declaration has no explicit initializer and other has an explicit initializer.

In this declaration

MyClass *myObject;

the pointer is uninitialized and has an indeterminate value if it is declared in a block scope without the storage class specifier static.

If it is declared in a namespace or with the storage class specifier static it is initialized as a null pointer. That is in this case the declaration is equivalent to

MyClass *myObject = nullptr;

In this declaration

MyClass *myObject = new MyClass();

the pointer is initialized by the address of a dynamically allocated object.

You may also rewrite the last declaration like

auto myObject = new MyClass();

because the type of the name myObject will be deduced from its initializer that is from the expression new MyClass().

Pay attention to that you may split this declaration

MyClass *myObject = new MyClass();

into two statements like

MyClass *myObject;
myObject = new MyClass();

CodePudding user response:

int a;

Does it have any meaningful value? Nothing because 'a' is not initialized.

int a = 5;

Does it have any meaningful value? Yes. 'a' has been initialized to value of 5.

In the same way

MyClass *myObject;

Does it have any meaningful value? No. myObject is not initialized. So it has some junk / random value.

MyClass *myObject = new MyClass();

Does it have any meaningful value? Yes. Sufficient memory to hold 'Myclass' has been allocated dynamically and myObject is pointing to starting of the allocated memory.

  • Related