I have two cases for allocation of memory using new operator.
class xx{
public: int x;
xx(){}
~xx(){}
};
class yy : public xx {
public: int y;
yy(){}
~yy(){}
};
int main(int argc, char *argv[])
{
yy *y1 = new yy(); //y1 constructor is called
//CASE-1
yy *y2 = y1;
//CASE-2
yy *y3 = new (y1) yy();
return 0;
}
In CASE-1 I am just allocating y1 memory to y2 without destroying y1(shallow copy). Here constructor will not be called.
In CASE-2 I am allocating y1 memory to y3 to the address destroying y1. Here constructor of y3 will be called. But destructor of y1 is not called. According to my understanding application has to take precautions for null value check while using y1 and y2 in future code.
So basically I want to understand the scenarios where CASE-2 is useful as compared to CASE-1. Thanks in advance.