COMS 261

COMS 261
Computer Science I
Title: Classes
Date: November 7, 2005
Lecture Number: 28
1
Announcements
2
Review
• Classes
– User defined data types
– Constructors
• Default
– Constructors
• With parameters
– Constructors
• Parameters with default values
3
Outline
• Classes
– Copy constructor
4
Classes
• Copy constructor
– VEC v1(1.2f, 3.4f);
– VEC v2(v1);
• Uses the copy constructor
• Creates v2, an independent object that contains
a copy of the data members of v1
v1.x = 1.2;
v1.y = 3.4;
v2.x = 1.2;
v2.y = 3.4;
Same values as
v1, but a different
object
Copy Constructor
– Syntax error when compiling
• VEC::VEC(VEC v) { … }
– Since, call by value requires we make a copy of the
vector v when calling the copy constructor
– The copy constructor would be called over and over
int main () {
VEC v1;
VEC v2(v1);
Call the copy constructor
Call by value make a
copy of v1
Copy Constructor
• Copy constructor cannot us call by value
–Only other choice is call by reference
• VEC::VEC(VEC& v) { … }
–Should the copy constructor ever
change the data member values of the
reference parameter?
• No, it should only read the values but not
change them
• Make the parameter a const reference
Copy Constructor
• vec.h: definition file
• vec.cpp: implementation file
Run CodeWarrior vec01
• Caution
– If you don’t provide an implementation of the
copy constructor, the compiler will supply
one
• It may not do what you think it will
Assignment Operator
• It would be nice to assign one VEC
object to another
– v1 = v2;
• To do this we must overload the
assignment operator (=) to define a
function when a VEC object is on both
the lhs and the rhs
Assignment Operator
• Should there be any arguments?
– Yes, the VEC we wish to assign
– Avoid making a copy, use call by reference
• Should the assignment operator change
the RHS?
– No, make it a const reference
– VEC& operator=(const VEC& v);
Run CodeWarrior vec03
Assignment Operator
• The assignment operator for this class
does not behave the way the primitive
data types do
– They allow chaining
• A = B = C;
– What happens if we try to chain the VEC
assignment operator?
– How do we get around this?