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
I've found a situation that let me think about that syntax. Consider a smart pointer to a
Base
class and that has to hold a pointer to a derived class and you would like to access some non-virtual things of the derived class after the construction. In this case something like this is legal and may not be so bad:Finally I still preferred the small arrows to the weird ampersands:
But I think that in this a case is just a matter of taste, especially if you access a consistent number of methods.
Other things that lead either to leaks or
delete &d;
are just bad, bad, bad.This:
is pretty much equivalent to this:
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:
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: