Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ pointer and reference with new keyword when instantiating

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

like image 231
tim Avatar asked Feb 15 '12 00:02

tim


People also ask

Does the new keyword return a pointer?

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.

When should I use references and when should I use pointers?

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.

Does new keyword work in C?

No, new and delete are not supported in C.

Why new keyword is used in CPP?

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.


1 Answers

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();
like image 127
Oliver Charlesworth Avatar answered Oct 15 '22 00:10

Oliver Charlesworth