Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A *a = new A(); Does this create a pointer or an object?

Tags:

A *a = new A(); 

Does this create a pointer or an object?

I am a c++ beginner, so I want to understand this difference.

like image 358
Chinmoy Avatar asked Apr 20 '13 06:04

Chinmoy


People also ask

Is pointer an object?

A pointer stores the memory address of a variable. When you pass a pointer (to an object) for a function as a parameter, it means that function will have access to that object through it's memory address instead of a new object being created on the stack.

What is * this pointer in C++?

The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object. Friend functions do not have a this pointer, because friends are not members of a class. Only member functions have a this pointer.

What does * mean in pointer?

The asterisk * used to declare a pointer is the same asterisk used for multiplication.


2 Answers

Both: you created a new instance of A (an object), and created a pointer to it called a.

You could separate it into two statements:

A *a;        // Declare `a` of type: pointer to `A`  a = new A(); // create a new instance of `A` and              // assign the resulting pointer to `a` 
like image 193
Paul Avatar answered Sep 22 '22 22:09

Paul


This creates an object of type A on the heap, and stores a pointer to it in a (that is stored on the stack).

P.S. Don't forget to call delete a when you're done with it, so that A can be destroyed and its memory given back to the heap. Better still, turn a into a smart pointer.

like image 39
NPE Avatar answered Sep 23 '22 22:09

NPE