|
|
|
Lecture 23 — classes in C++
|
|
|
|
|
class declaration
|
|
|
|
|
see posted files for examples
|
|
|
|
|
declaration usually given in header
|
|
|
|
|
method prototypes and fields
|
|
|
|
|
definition of methods given in source file using ClassName::
|
|
|
|
|
three access modifiers
|
|
|
|
|
public, protected, private
|
|
|
|
|
private by default
|
|
|
|
|
constructors
|
|
|
|
|
if no constructor given, compiler provides implicit zero-argument constructor
|
|
|
|
|
compiler also provides implicit copy constructor
|
|
|
|
|
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
|
|
|
|
|
destructor
|
|
|
|
|
used to “clean up” an instance
|
|
|
|
|
called when an instance is deallocated by delete
|
|
|
|
|
called automatically for stack-allocated instances
|
|
|
|
|
operator overloading
|
|
|
|
|
Rule of Three: if you implement one of the following, then you probably need to implement all three
|
|
|
|
|
copy constructor
|
|
|
|
|
destructor
|
|
|
|
|
assignment operator
|
|
|
|
|
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?)
|
|
|
|
|
overload << if you want to be able to print your object with cout
|
|
|
|
|
analogus to overloading toString in Java
|
|
|