Chapter 2 Object-oriented Design
2.1 instructions
2.1.1 Goals
Software implementtions should achieve **robustness, adaptbility, and reusability**.
2.1.2 Object-Oriented Design Principles
Abstraction
Encapsulation
Modularity
2.1.3 Design Patterns
Some of the algorithms:
Recursion
Amortization
Divide-and-conquer
Prune-and-search(decrease-and-conquer)
Brute force
The greedy method
Dynamic programming
2.2 Inheritance and Polymorphism
Inheritance in C++
A generic class is also known as a **base class, parent class, or superclass**.
Polymorphism
Examples of Inheritance and Class Casting
We consider an example of several classes that print numeric progressions.
Arithmetic progression (increment 1) 0,1,2,3,4,5, . . .
Arithmetic progression (increment 3) 0,3,6,9,12, . . .
Geometric progression (base 2) 1,2,4,8,16,32, . . .
Geometric progression (base 3) 1,3,9,27,81, . . .
firstValue(): Reset the progression to the first value and return it.
nextValue(): Step the progression to the next value and return it.
printProgression(n): Reset the progression and print its first n values.
class Progression {
public:
Progression(long f = 0)
: first(f), cur(f) { } virtual ˜Progression() { };
void printProgression(int n);
protected:
virtual long firstValue();
virtual long nextValue();
protected:
long first;
long cur;
};
void Progression::printProgression(int n) {
cout << firstValue();
for (int i = 2; i <= n; i++)
cout << ’ ’ << nextValue();
cout << endl;
}
interface and Abstrac Classes
2.3 Templates
Inheritance is only one mechanism that C++ provides in support of polymorphism.
In this section, we consider another way—using templates.
2.3.1 Function Templates
template <typename T>
T genericMin(T a, T b) { // returns the minimum of a and b
return (a < b ? a : b);
}
The declaration takes the form of the keyword “template” followed by the notation
<typename T>, which is the parameter list for the template. In this case, there is
just one parameter T. The keyword “typename” indicates that T is the name of
some type.
Class Templates
In addition to function templates, C++ allows classes to be templated, which is a powerful mechanism because it allows is to provide one data structure declaration that can be applied to many different tepes. In fact, the STL uses class templates extensively.
template <typename T>
class BasicVector {
public:
BasicVector(int capac = 10);
T& operator[ ](int i)
{ return a[i]; }
private:
T* a;
int capacity;
};
We have defined one member function (the indexing operator) within the class
body, and below we show how the other member function (the constructor) can
be defined outside the class body. The constructor initializes the capacity value andallocates the array storage.
template <typename T>
BasicVector<T>::BasicVector(int capac) { capacity = capac;
a = new T[capacity];
}
BasicVector<int> iv(5);
BasicVector<double> dv(20);
BasicVector<string> sv(10);