V Lecture 23 — classes in C++
V class declaration
* see posted files for examples
V declaration usually given in header
* method prototypes and fields
* definition of methods given in source file using ClassName::
V three access modifiers
* public, protected, private
* private by default
V constructors
* if no constructor given, compiler provides implicit zero-argument constructor
V compiler also provides implicit copy constructor
V a copy constructor is used whenever an instance is being copied
* passed by value
* a new instance is being constructed from an existing instance
* the default copy constructor just tries to copy over each field (perhaps invoking additional copy constructors)
* a copy-constructor by definition takes a reference
parameter (else we’d need to copy the parameter, but
that’s what we’re defining!) of the same type
V destructor
* used to “clean up” an instance
* called when an instance is deallocated by delete
* called automatically for stack-allocated instances
V operator overloading
V Rule of Three: if you implement one of the following, then you probably need to implement all three
* copy constructor
* destructor
* assignment operator
V copy constructor vs. assignment
* copy constructor initializes a new bag of bits (new
variable or parameter)
* assignment (=) replaces an existing value with a new
one – may need to clean up old state (free heap data?)
V overload << if you want to be able to print your object with cout
* analogus to overloading toString in Java