Hi All,
I've got an array of objects, during the execution of the program I'd
like to assign a particular object to a certain element in the object
array. The sample code's like this...
class ClassA
{
public:
ClassA()
: m(rand() % 173) { cout<<"\nRandom Constructor: "<<m ; }
ClassA(int val)
: m(val) { cout<<"\nConstr ucted: "<<m ; }
~ClassA() { cout<<"\n\nDest ructor: "<<m ; }
private:
int m ;
} ;
int main()
{
srand((unsigned )time(NULL)) ;
const int size = 3 ;
ClassA *c = new ClassA[size] ;
c[0] = ClassA(200) ;
c[0] = ClassA(201) ;
delete[] c ;
return 0 ;
}
//Output...
Random Constructor: 50 <--- (object vanishes without destructor call)
Random Constructor: 38
Random Constructor: 148
Constructed: 200
Destructor: 200
Constructed: 201
Destructor: 201 <--- (1. 1st destructor call for this object)
Destructor: 148
Destructor: 38
Destructor: 201 <--- (2. object is being destroyed twice or has it
replaced the very first object?)
As I've pointed out in the output, the the destructor for the 1st
object never gets called, whereas the destructor for the object created
with data = 201 gets called twice. Is this the case or is it the very
first object which is in fact getting destroyed in (2) ?
Also, what's the best practice for such a situation?
I've got an array of objects, during the execution of the program I'd
like to assign a particular object to a certain element in the object
array. The sample code's like this...
class ClassA
{
public:
ClassA()
: m(rand() % 173) { cout<<"\nRandom Constructor: "<<m ; }
ClassA(int val)
: m(val) { cout<<"\nConstr ucted: "<<m ; }
~ClassA() { cout<<"\n\nDest ructor: "<<m ; }
private:
int m ;
} ;
int main()
{
srand((unsigned )time(NULL)) ;
const int size = 3 ;
ClassA *c = new ClassA[size] ;
c[0] = ClassA(200) ;
c[0] = ClassA(201) ;
delete[] c ;
return 0 ;
}
//Output...
Random Constructor: 50 <--- (object vanishes without destructor call)
Random Constructor: 38
Random Constructor: 148
Constructed: 200
Destructor: 200
Constructed: 201
Destructor: 201 <--- (1. 1st destructor call for this object)
Destructor: 148
Destructor: 38
Destructor: 201 <--- (2. object is being destroyed twice or has it
replaced the very first object?)
As I've pointed out in the output, the the destructor for the 1st
object never gets called, whereas the destructor for the object created
with data = 201 gets called twice. Is this the case or is it the very
first object which is in fact getting destroyed in (2) ?
Also, what's the best practice for such a situation?
Comment