/* File: oop3.cpp ... a variation of the previous example ... If the pure virtual () operator in the abstract base class is defined as a const function, then the apply() function can be given a temporary object produced by the constructor without storing it in a variable: apply (AddX(5), B, 10) ; */ #include using namespace std ; //------------------------------------------- class Int2Int { public: virtual int operator() (int) const = 0 ; // pure virtual } ; //------------------------------------------- class AddX : public Int2Int { private: int m_offset ; public: AddX(int offset = 0) { m_offset = offset ; } int operator()(int m) const { return m + m_offset ; } } ; //------------------------------------------- class Mult3 : public Int2Int { public: int operator()(int m) const { return 3*m ; } } ; //------------------------------------------- void apply(const 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} ; printf("Before:\n") ; for (int i=0 ; i < 10 ; i++) { cout << " B[" << i << "] = " << B[i] << endl ; } apply (AddX(3), B, 10) ; printf("\n\nAfter calling apply(AddX(3), B, 10):\n") ; for (int i=0 ; i < 10 ; i++) { cout << " B[" << i << "] = " << B[i] << endl ; } apply (AddX(5), B, 10) ; printf("\n\nAfter calling apply(AddX(5), B, 10):\n") ; for (int i=0 ; i < 10 ; i++) { cout << " B[" << i << "] = " << B[i] << endl ; } apply (Mult3(), B, 10) ; printf("\n\nAfter calling apply(Mult3(), B, 10):\n") ; for (int i=0 ; i < 10 ; i++) { cout << " B[" << i << "] = " << B[i] << endl ; } }