Last semester
const int Number=1; //declaring a constant
void print_data (const Student[], int size); //arrays as parameters
Arrays are passed by reference by default, const ensures they are not modified.
Class objects are often passed by reference with const
Why: it is more efficient to pass the address of an object (&) and
then restrain it to be const.
E.g.
bool operator==(const fractionType&) const;
could be
bool operator==(fractionType) const;
but that would require copying the whole object, not just its address.
What does the const at the end do?
void reduce();
bool zero() const;
(reduce changes the object to which it is applied, zero does not)
Convention: use const anywhere you can--it makes your intentions explicit.
Caveat: an object which has been made 'const', for example by being passed as a parameter
in the 'const &' way, can only have those of its methods that are explicitly
declared 'const' called.
Therefore class methods that don't change the object are best declared 'const' so that they are not prevented from being called when an
object of the class has somehow acquired 'const' status.
E.g.
const rationalType rationalType::operator=(const fractionType& otherFraction)
{
numerator =otherFraction.getNumerator();
denominator=otherFraction.getDenominator();
return *this;
}
otherFraction is passed as const, thus getNumerator and getDenominator must be const methods.
Why the const at the beginning?
The parameter is the pointer (this) which is unchanged. The object pointed to by this (*this) is changed.
See the solution to assn2 for an alternate way to overload ==
What is the difference between const in these:
friend ostream& operator<< (ostream&, const fractionType&);
friend istream& operator>> (istream&, fractionType&);
Why is one const and the other not?
(>> alters the rhs element, << does not)