Dumb question, but whenever you call new, do you always have a pointer?
SomeClass *person = new SomeClass();
And is that because you need a poi
The new expression returns a pointer, but you can use it with "smart pointer" classes (e.g. from Boost). So:
boost::shared_ptrperson(new SomePerson);
I should also point out that, though you may be used to using the parentheses if you come from a Java background, in C++, the parentheses are not needed when using the default constructor. So, for example, one ordinarily writes new T
when default constructing, but one writes new T(param)
, or new T(param1,...,paramN)
when constructing an object using a constructor other than the default.
Yes, that is correct; one could, theoretically, write (new SomePerson)->doSomething(), but that would be a memory leak; C++ does not have garbage collection, so it is necessary to store the result of the new expression in something (a pointer or a smart pointer) so that it can be properly deallocated.