A function can return value a value of type T in one of several different ways . Which one these is correct
All of them are correct.
Give a short declaration of a function that returns its value by these mechanism:
1. By value
T test(T t)
{
return t;
}
2. By const value
const T test(const T t)
{
...
return t;
}
3. By reference
T& test(T& t)
{
...
return *t;
}
4. By const reference
const T& test(const T& t)
{
...
return *t;
}
5. By lazy evaluation
T get()
{
if (calculated)
{
return result;
}
calculated = true;
return result = function();
}
Comment on const method of function return value
A function becomes const when the const keyword is used in the function’s declaration. The idea of const functions is not to allow them to modify the object on which they are called.
A const member function can be called by any type of object. Non-const functions can be called by non-const objects only.
Here is the syntax of const member function in C++ language,
datatype function_name const();
In the below code we have made i as constant, hence if we try to
change its value, we will get compile time error. Though we can use
it for substitution for other variables.
int main
{
const int i = 17;
const int j = i + 17;
i++;
}
Comment on where there is danger involved in returning a reference of any kind from a function.
Never return any kind of reference of a local / Temporary variable.
Which one of these returns and L value and which is an R value.
by value -- R-value
lazy evalution-- It can return L-value or R-value (based on implementation)
reference-- L-value
const value-- R-value
const reference--- L-value
Get Answers For Free
Most questions answered within 1 hours.