Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doubt on a C++ interview question

I have read Answers to C++ interview questions among which there is one that puzzles me:

Q: When are temporary variables created by C++ compiler?

A: Provided that function parameter is a "const reference", compiler generates temporary variable in following 2 ways.

a) The actual argument is the correct type, but it isn't Lvalue

double Cube(const double & num)
{
  num = num * num * num;
  return num;
}

double temp = 2.0;
double value = cube(3.0 + temp); // argument is a expression and not a Lvalue

b) The actual argument is of the wrong type, but of a type that can be converted to the correct type

 long temp = 3L;
 double value = cuberoot(temp); // long to double conversion

My question is once the function argument is a const reference, why does the compiler generate the temporary variable, isn't that self-contradictory? Also, should the function Cube fail to compile because it modifies the const argument?

like image 993
Tracy Avatar asked Dec 12 '22 19:12

Tracy


2 Answers

I don't see anything self-contradictory here. If the argument is not an lvalue, or is of wrong type, the reference cannot be attached directly to the argument for obvious reasons; hence the need for an intermediate temporary of the correct type. The reference is attached to that temporary instead.

The Cube function is indeed broken (ill-formed) since it attempts to modify a const value.

like image 189
AnT Avatar answered Dec 27 '22 11:12

AnT


Looks wrong to me - and gcc generates an error:

const_ref.cpp: In function ‘double cube(const double&)’:
const_ref.cpp:3: error: assignment of read-only reference ‘num’
like image 33
Paul R Avatar answered Dec 27 '22 09:12

Paul R