please answer this question , merci

i'm a beginner, please help me !

what is purpose of key words "const" and symbol "&" in 2 function? :

1/ Fraction Fraction::plus (const Fraction &x);

2/ int & Array::getCell(int loCaTiOn) const;

thanks so much !!!
Last edited on
const stands for constant. It is used to declared identifiers that may not be changed.

The ampersand creates an address for the identifier it preceeds. As an argument it means that the function will not make a copy of the variable passed to it, but will instead use the same variable used to call the function. It used together with const, the function will not make a copy, potentially conserving resources (often used with user defined types), and it also promises that it will not alter the original variable.

When used as a return type, const disallows the calling code to change the memory at the address it returns. In example 2, the function is returning the memory address to the information at the indicated cell. This way, the calling code may read the value stored in the cell, but not make changes.
I reckon the const and static keywords are two of the most
confusing things when learning c++.

int & Array::getCell(int loCaTiOn) const;
This means that the member function getCell will not
modify the (Array) object member data for which it is called (this will be enforced by the compiler).
In other words it can be condidered a 'readonly' function.
So a const member function can be used to get a value (as shown) , but would be useless for a set function which needs to modify the object.
Last edited on
Topic archived. No new replies allowed.