Answer the question
In order to leave comments, you need to log in
Why can a non-const method be called on a temporary object?
class X {
int i;
public:
X(int ii = 0);
void modify();
};
X::X(int ii) { i = ii; }
void X::modify() { i++; }
X f5() {
return X();
}
const X f6() {
return X();
}
void f7(X& x) { // Pass by non-const reference
x.modify();
}
int main() {
f5() = X(1); // OK -- non-const return value
f5().modify(); // OK
// Causes compile-time errors:
//! f7(f5());
//! f6() = X(1);
//! f6().modify();
//! f7(f6());
}
Answer the question
In order to leave comments, you need to log in
Regarding the call of non-constant methods - why did you get the idea that they should not be possible? Temporary objects do not have const qualifiers. Otherwise it would be impossible to do things like SomethingBuilder().WithA().WithB().Finalize()
.
//! f6() = X(1);
//! f6().modify();
//! f7(f5());
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question