* operator)
void play(const Video &video) {…}
T &) should be used.
void minmax(int x, int y, int z, int &min, int &max);
void read(Rational &r);
class Rational {
…
… add(const Rational &r);
…
};
int, long, double, bool, char, float) and is not being modified, the parameter
should be passed by-value (T).
int abs(int i);
*this) From Being Modifiedthis), e.g.
vector does not change the vector
Rational to a receiving Rational and returning a third (new) Rational
as the result does not change the receiver
addInPlace DOES change the receiver.
const there is no 'obvious' way to do so for the receiver.
class Rational {
…
int getNumerator() const;
void print() const;
…
};
x + f(y)
x = f(y);
x = f(y)
System.out.println(f(y));
g(a, b, f(y), d);
int &f() {
int x = 10;
return x;
}
…
int y = f(); // trying to assign to y a value from the location of x, which is no longer valid
int *f() {
int x = 10;
return &x;
}
…
int y = *f(); // trying to assign to y a value by dereferencing a pointer to the location of x, which is no longer a valid location
Rational multiply(const Rational &r) { Rational result; … return result; }
result must be returned by value, since it goes out of scope upon function exit
int f();
Rational &multiplyInPlace(const Rational &r) { … return *this;; }
class Simple {
public:
Simple(int v) : val(v) {}
double &value() {return val;}
private:
double val;
};
…
Simple simple(12);
cout << simple.value() << endl; // prints 12
simple.value() = 15; // assign 15 to simple's val
val —
not its value (rvalue) — is being returned
x = y, since y appears in a context requiring an rvalue (its 'value'), we go to
the location of y and extract its value/contents.
x — the left operand of the assignment — we are interested in its lvalue (it's location)
where we store the value obtained from the right hand operand