A *a = new A();
Does this create a pointer or an object?
I am a c++ beginner, so I want to understand this difference.
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.
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.
The asterisk * used to declare a pointer is the same asterisk used for multiplication.
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`
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With