...understanding this example? Hi all:
I would be very grateful if someone could help me understand an example of using "const" in a function declaration.
In general I understand that const should be used in a function declaration to alert people that the function can deal with constant objects. But I don't understand this example in my text:
Using const in function declarations can reduce errors without compromising safety or efficiency. For example, recall the declaration of operator* for the Wood class:
const Wood operator*(const Wood& lhs, const Wood& rhs);
Why should the return type be const? Otherwise, you could write code like this:
Wood a, b, c; (a * b) = c;
This would not be allowed by a built-in type. Making operator* return const disallows this for the Wood type too. End of example...
This is probably a dumb question, but I don't understand what is wrong with writing code like: Wood a, b, c; (a * b) = c; What is the problem with this? Thanks for any help!
I would be very grateful if someone could help me understand an example of using "const" in a function declaration.
In general I understand that const should be used in a function declaration to alert people that the function can deal with constant objects. But I don't understand this example in my text:
Using const in function declarations can reduce errors without compromising safety or efficiency. For example, recall the declaration of operator* for the Wood class:
const Wood operator*(const Wood& lhs, const Wood& rhs);
Why should the return type be const? Otherwise, you could write code like this:
Wood a, b, c; (a * b) = c;
This would not be allowed by a built-in type. Making operator* return const disallows this for the Wood type too. End of example...
This is probably a dumb question, but I don't understand what is wrong with writing code like: Wood a, b, c; (a * b) = c; What is the problem with this? Thanks for any help!