// B2.6.cpp : Defines the entry point for the console application. // // Please provide the definition of a function that accepts a pointer // to a function with the signature int func(X &x), invokes the function, // and returns the value computed if positive. Otherwise it throws an // exception with an error message. #include "stdafx.h" #include using namespace std; class X { public: X(int i) : val(i) { } int& value() { return val; } private: int val; }; int fun1(X &x) { return x.value(); } int fun2(X &x) { return (x.value()*x.value()); } //// answer /////////////////////////////////////////////// int invoker(int(*fPtr)(X &x), X &x) { int test = fPtr(x); if(test <= 0) { exception e("exception thrown: non positive result"); throw e; } return fPtr(x); } /////////////////////////////////////////////////////////// int _tmain(int argc, _TCHAR* argv[]) { std::cout << "\n Exam B2 - Question #6 " << "\n =======================\n"; try { cout << "\n value returned by invoker = " << invoker(fun1,X(5)); cout << "\n value returned by invoker = " << invoker(fun2,X(5)); cout << "\n value returned by invoker = " << invoker(fun1,X(-5)); } catch(exception& e) { cout << "\n " << e.what(); } cout << "\n\n"; return 0; }