class Point {
public:
Point(const Point& p) {
x = p.x;
y = p.y;
}
Point& Point::operator=(const Point& rhs) {
if (this != &rhs) {
// delete old value/free
// delete [] _name;
// name = new char[strlen(rhs._name)+1];
// strncpy(..);
x = rhs.x;
y = rhs.y;
return *this;
}
};
If class has heap memory:
you need ctor/dtor-virtual, assign and deep copy.
A copy constructor is used to initialize a newly declared variable from an existing variable. This makes a deep copy like assignment, but it is somewhat simpler:
1. There is no need to test to see if it is being initialized from itself.
2. There is no need to clean up (eg, delete) an existing value (there is none).
3. A reference to itself is not returned.
4. assignment: return *this: allow x=y=z;
Wednesday, August 19, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment