When I want to instantiate a class in C++ I usually go this way
Book bk = new Book();
My professor recently did this
Book &bk = *new Book();
He only told me that he would use a reference to be able to use the dot (eg bk.getTitle();) operator instead of arrow (eg bk->getTitle();). I understand this part of the code but what happens when you use the * operator in combination with new?
Thanks in advance
the full example code can be found here it is the arraystack in the main function
The new operator does not create a separate pointer variable. It allocates a block of memory, calls constructors (if any), and returns to you the address of the block of memory. An expression in C++ has a value and a data type.
Use references when you can, and pointers when you have to. References are usually preferred over pointers whenever you don't need “reseating”. This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside.
No, new and delete are not supported in C.
When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated. Use the delete operator to deallocate the memory allocated by the new operator.
This:
Book &bk = *new Book();
is pretty much equivalent to this:
Book *p = new Book(); // Pointer to new book
Book &bk = *p; // Reference to that book
But there's one crucial difference; in the original code, you don't have a pointer which you can use to delete
the dynamically-allocated object when you're done with it, so you've effectively created a memory leak.
Of course, you could do this:
delete &bk;
but that's extremely non-idiomatic C++, and very likely to cause problems later.
In summary, there's absolutely no good reason to write code like this, so don't do it. Either of the following is fine:
Book bk;
Book bk = Book();
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