C++ Lecture 7
[Previous Lecture]
[Lecture Index]
[Next Lecture]
Defensive Class Design
Common problems caused by mis-use of classes:
- passing class by value
(copy is created with shared contents, then destroyed)
- assigning one instance from another
(old contents overwritten, new contents shared)
Solution: design classes to deal with or prevent misuse
- define a copy constructor, if necessary/possible, that
- creates a completely independent copy
- define operator= method, if necessary/possible, that
- releases old resources
- creates a completely independent copy
Also, handle assignment to self.
- if not possible, create a private
copy constructor/operator= which print an error if called
Note: If your destructor does anything, you probably
need a copy constructor and assignment operator.
Intro to Templates
Example:
template <class XYZ>
XYZ &
myMin(XYZ &a, XYZ &b)
{
if (a < b)
return a;
else
return b;
}
int
main()
{
cout << myMin(10, 4) << endl;
cout << myMin(-2.4, 8.9) << endl;
return 0;
}
Standard Template Library Intro
Library has templates for
- containers (vector, list, map, etc.)
- algorithms (sort, find, etc.)
- and more
Containers:
-
Each container has an iterator type,
e.g., vector<int>::iterator i;
-
Iterator is used to access elements:
- *i is a reference to element i `points' to
- ++i moves iterator forward one position
- --i moves iterator backward one position
-
Common methods:
-
iterator begin(): returns iterator positioned at start
-
iterator end(): returns iterator positioned past end
-
push_back(T e): add element to end
-
push_frontT e): add element to start
-
insert(iterator i, T e): insert in specified location
-
int size(): number of elements stored
-
Types of containers:
- vector<T>: similar to an array
- list<T>: similar to a list
- map<T>: similar to a hash table
-
Some containers have extra methods,
eg, vector<T> has:
- [int i] references element at index i
- at(int i) references element at index i, does range check
- resize(int n) change size of vector
[Previous Lecture]
[Lecture Index]
[Next Lecture]