As you have seen, it is possible to overload the assignment operator relative to a class. By default, when the assignment operator is applied to an object, a bitwise copy of the object on the right side is put into the object on the left. If this is what you want there is no reason to provide your own operator=( ) function. However, there are cases in which a strict bitwise copy is not desirable (e.g. cases in which object allocates memory). In these types of situations, you will want to provide a special assignment operator. Here is another version of strtype class that overload the = operator so that the point p is not overwritten by the assignment operation.
#include
#include
#include
using namespace std;
class strtype {
char *p;
int len;
public:
strtype(char *s); // constructor
∼strtype( ) { // destructor
cout << "Freeing " << (unsigned) p << "\n";
delete [ ] p;
}
char *get( ) { return p; }
strtype &operator=(strtype &ob);
};
// Constructor
strtype::strtype(char *s) {
int l;
l = strlen(s) + 1;
p = new char [l];
if (!p) {
cout << "Allocation error\n";
exit(1);
}
len = 1;
strcpy(p, s);
}
// Assign an object
strtype &strtype::operator=(strtype &ob) {
// see if more memory is needed
if (len < ob.len) {// need to allocate more memory
delete [ ] p;
p = new char [ob.len];
if (!p) {
cout << "Allocation error\n";
exit(1);
}
}
len = ob.len;
strcpy(p, ob.p);
return *this;
}
int main( ) {
strtype a("Hello"), b("there");
cout << a.get( ) << "\n";
cout << b.get( ) << "\n";
a = b; // now p is not overwritten
cout << a.get( ) << "\n";
cout << b.get( ) << "\n";
return 0;
}
Notice two important features about the operator=( ) function:
• It takes a reference parameter (prevent a copy of the object on the right side from being made).
• It returns a reference, not an object (prevent a temporary object from being created).
No comments:
Post a Comment