1

The program below compiles (with gcc), but should it? I would have thought that V1(1.0) created below is a constant, and so a non const method could not be invoked on it.

class V{
  double v;
 public:
  V(double v1){ v = v1;}
  void clear(){ v = 0;}
};

int main(){
  V(1.0).clear();
}

Compare this to a function "void f(int &t){}" which cannot be called as "f(1)", because 1 is a constant which cannot be a value for a non-const reference t.

Ekalavya
  • 969
  • 1
  • 9
  • 14

2 Answers2

3

V(1.0) calls the constructor, which initializes double v1 by copy. So you have a temporary with a copy of the literal.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

You seem to be confusing constants with r-values. f(1) would be illegal because 1 is not an l-value. V(1.0) is not a constant, but a temporary.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625