/* File: oop2.cpp The OOP mechanisms for inheritance and late binding (i.e., virtual functions) can be used to allow any "function" derived from the class Int2Int to be passed to apply(). */ #include using namespace std ; //------------------------------------------- class Int2Int { public: virtual int operator() (int) = 0 ; // pure virtual } ; //------------------------------------------- class AddX : public Int2Int { private: int m_offset ; public: AddX(int offset = 0) { m_offset = offset ; } int operator()(int m) { return m + m_offset ; } } ; //------------------------------------------- class Mult3 : public Int2Int { public: int operator()(int m) { return 3*m ; } } ; //------------------------------------------- void apply(Int2Int& f, int A[], int n) { for (int i=0 ; i < n ; i++) { A[i] = f( A[i] ) ; } } int main () { int B[10] = { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19} ; AddX add3(3) ; AddX add5(5) ; printf("Before:\n") ; for (int i=0 ; i < 10 ; i++) { cout << " B[" << i << "] = " << B[i] << endl ; } apply (add3, B, 10) ; printf("\n\nAfter calling apply(add3, B, 10):\n") ; for (int i=0 ; i < 10 ; i++) { cout << " B[" << i << "] = " << B[i] << endl ; } apply (add5, B, 10) ; printf("\n\nAfter calling apply(add5, B, 10):\n") ; for (int i=0 ; i < 10 ; i++) { cout << " B[" << i << "] = " << B[i] << endl ; } Mult3 times3 ; apply (times3, B, 10) ; printf("\n\nAfter calling apply(times3, B, 10):\n") ; for (int i=0 ; i < 10 ; i++) { cout << " B[" << i << "] = " << B[i] << endl ; } }