I’m using the code under “Constructors and destructors” here
Basically, i would like to combine it with the pointer construction under
“Pointers to classes” (a little below) which i find really neat.
Now this works:
int main () {
CRectangle * prect; //l2
CRectangle rect (3,4); //l3
prect = ▭ //l4
cout << "rect area: " << (*prect).area() << endl;
return 0;
}
My questions is, can we replace l2-l4 by a more elegant method
not requiring the creation of rect on line 3?
To create an object without requiring any automatic variables (such as
rectin your code above) you must use thenewoperator. Objects created with thenewoperator are stored in the free store, and thenewexpression evaluates into a pointer to the newly created object.Now, one could go on and say,
newoperator is the answer and that’s it, but it’s actually not: it does not answer the question of replacing those couple of lines with a more elegant solution, because it wouldn’t be one.The rest of this answer goes on a tangent of how
newcould be used.Unlike automatic objects, objects stored in the free store are not automatically destructed, but rather their life-time and destruction is controlled by the
deleteoperator (you should delete objects you no longer need to free resources). To ensure destruction, you should always store the pointer from anewexpression into what’s called a smart pointer. A good, simple rule that carries one far: use thenewoperator only inside a smart pointer constructor (unless you know what you’re doing).There are several smart pointers in C++11, while earlier versions of the standard only defined one, the
auto_ptr. Perhaps due to it’s quirks, or simply because it got a replacement, it’s actually deprecated in C++11, and shouldn’t probably be used in new code, at least not in C++11 (now, this is an opinion).An example of smart pointer use: