(1) Is following code at Line-1 an undefined behavior for different compilers ? (it works fine with linux g++ compiler)
(2) If you comment the operator = (), and try to assign the object with a pointer (Line-3), still the code gets compiled, Why ? (actually it's instantiates the constructor !)
(3) In continuation, Why does the pn.size get garbaged when assigned with a pointer ?
(2) If you comment the operator = (), and try to assign the object with a pointer (Line-3), still the code gets compiled, Why ? (actually it's instantiates the constructor !)
(3) In continuation, Why does the pn.size get garbaged when assigned with a pointer ?
Code:
template<class TYPE>
struct Arr{
TYPE *ptr;
int size;
Arr(TYPE *p=0) : ptr(p) { }
// Arr& operator = (TYPE *p) { delete[] ptr; ptr = p; return *this;}
void print () { cout<<"ptr = "<<ptr<<" and size = "<<size<<endl; }
~Arr() { delete[] ptr; }
};
int main()
{
Arr<int> pn = new int[pn.size = 10]; // Line-1
pn.print(); // Line-2
pn = new int[pn.size = 5]; // Line-3
pn.print(); // Line-4
}
Comment