Monday, November 2, 2009

Copy constructor and assignment operator for DsStack class

1. copy constructor
1.1 Stack::Stack(const DString data){
this->top=(SNode*)0;
Push(data);
}
1.2 Stack::Stack(const Stack& t){
this->top=(SNode*)0;
*this = t;
}

2. assignment operator
Stack& Stack::operator=(const Stack& t){
while(!IsEmpty()){
Pop();
}
SNode* temp=t.top;
while(temp){
Push(temp->data);
temp=temp->next;
}
delete temp;
SNode* tem=this->top;
this->top=(SNode*)0;
while(tem){
Push(tem->data);
tem=tem->next;
}
delete tem;
return *this;
}

1 comment:

  1. In C++, assignment and copy construction are different because the copy constructor initializes uninitialized memory, whereas assignment starts with an existing initialized object. If your class contains instances of other classes as data members, the copy constructor must first construct these data members before it calls operator=. The result is that these members get initialized twice, as cctest shows. Got it? It's the same thing that happens with the default constructor when you initialize members using assignment instead of initializers.

    vitamin e

    ReplyDelete