class x{
int i;
public:
x(int ii=0);
void modify();
};
X f5(){
return X();
}
void f7(X& x){
x.modify();
}
int main(){
f7(f5()); <-----COMPILE ERROR THERE
}
Can someone please explain why does that error appear ?
class x{
int i;
public:
x(int ii=0);
void modify();
};
X f5(){
return X();
}
void f7(X& x){
x.modify();
}
int main(){
f7(f5()); <-----COMPILE ERROR THERE
}
Can someone please explain why does that error appear ?
It doesn't say const anywhere in the code!
Presumably it is moaning that you are passing an unnamed temporary value (i.e. return value from f5()) as a reference parameter which isn't legal (but may be allowed with a warning) since you don't want to be modifying an unnamed temporary value by accident.
Try doing
X myX = f5();
f7(myX);
instead, that should work...
EDIT: And we aren't psychic (try the math & psychics forum instead for that) please post the full error message and compiler you are using next time kthx ;)
I think I won the "in simpler terms" game!
I was going to suggest using a const reference for function f7 but it calls a function called modify() on the parameter passed, I guessed that might not be a good suggestion, so I made a poor joke instead ;)
class x{ int i; public: x(int ii=0); void modify(); }; X f5(){ return X(); } void f7(X& x){ x.modify(); } int main(){ f7(f5()); <-----COMPILE ERROR THERE }
Can someone please explain why does that error appear ?
Beyond the very descriptive and detailed descriptions, this could be a simple case of compiler differences biting you on the ass. The given code is valid for Visual Studio and unless you set warning level to 4, it won't even bitch about this. The very simple answer is that:
f7( f5() );
is actually illegal C++ yet VC cheats and allows it via a syntactic sugar addition. GCC on the other hand will pitch a fit and give you an error. The "fix" is simple:
temp = f5();
f7( temp );
So, if you have been using GCC and reading books with a VC source (pretty common unfortunately), you need to use the more explicit syntax, VC does this behind your back and hides it unless you set warnings to 4. (Not even sure VC warns about this at w4, think so though.)