CSCI 2270 Computer Science 2: Data Structures
Fall 2003
Karl Winklmann

Assignment operator, copy constructor, destructor

Thursday, September 11, 2003

 


Previous page | Next page | Latest page | Schedule and syllabus | Home Page | Programs | Table of contents | News archive | Dora

These are code fragments discussed in class.

Destructor

Canvas::~Canvas( )
{
    delete [] objects;
}

Assignment operator

void Canvas::operator =( const Canvas& canvas )
{
    if (this == &canvas) // self-assignment 'A=A', nothing to do
        return;

    delete [] objects;
    
    objects = new MovingObject [canvas.capacity];
    capacity = canvas.capacity;
    n = canvas.n;

    copy (canvas.objects, canvas.objects + canvas.capacity, objects);
}

Copy constructor

Canvas::Canvas( const Canvas& canvas )
{
    capacity = 8;
    objects = new MovingObject [capacity];
    n = 0;

    // instead of the three above lines a single line
    //     objects = NULL;
    // would also work

    *this = canvas;
}
 


© 2003 Karl Winklmann 3:08 PM, Tuesday, December 16, 2003