I took this example straight out of a book (Sams Teach Yourself C++ in One Hour a Day):
// Get the maximum of two values
template <typename objectType>
objectType& GetMax(const objectType& value1, const objectType& value2)
{
if (value1 > value2)
return value1;
else
return value2;
}
Essentially it is a very verbosely written template function to find the maximum between 2 values of any type.
I attempted to use the function as follows:
// Test the Max function
int x_int = 25;
int y_int = 40;
int max_int = GetMax(x_int, y_int);
cout << "max_int: " << max_int << endl;
double x_double = 1.1;
double y_double = 1.001;
double max_double = GetMax(x_double, y_double);
cout << "max_double: " << max_double << endl;
However, when I attempt to compile and run the code I get the following errors:
Error 1 error C2440: 'return' : cannot convert from 'const int' to 'int &'
Error 2 error C2440: 'return' : cannot convert from 'const int' to 'int &'
Error 3 error C2440: 'return' : cannot convert from 'const double' to 'double &'
Error 4 error C2440: 'return' : cannot convert from 'const double' to 'double &'
If I simply remove the & from the return type of the function it will compile and execute successfully.
Why can't I return a reference from this function? Is the book wrong, or is there something I am missing?
const&- JSF