Hi!
When do I need to declare const method? And when to use const references?
Some pseudo-code examples will be just fine.
Thanks!
Hi!
When do I need to declare const method? And when to use const references?
Some pseudo-code examples will be just fine.
Thanks!
Last edited by GaPe; 12-07-2005 at 03:41 AM. Reason: typing errors
Current projects:
1) User Interface Development Kit (C++)
2) HTML SDK (C++)
3) Classes (C++)
4) INI Editor (Delphi)
1. When you want to tell the compiler your member function doesn't modify data.
2. When you don't want things messing with you data but want them to use it.
Woop?
1. As a matter of course for all class functions that don't change the calling object. That way const objects as well as regular objects can call the function.When do I need to declare const method?
2. Passing by reference is more efficient since it avoids copying the argument for the function. However passing by reference means the class function can change the object you are sending to the function. If your function does not need to change the object you are sending it, then declare the function parameter const. That way if the code in the function mistakenly changes the object, the compiler will give you an error. That allows you to use the compiler to catch any programming mistakes you make--instead of having unintended things occur at runtime.
Last edited by 7stud; 12-07-2005 at 08:14 AM.
If you are unsure whether a methods should be const or not, make it const. Your compiler will complain if it shouldn't be const because it modifies an internal variable.
Simple, built-in types do not need to be passed by const-reference, but class types should always be passed by const reference unless you have reason to do otherwise. Reasons to do otherwise would include wanting to modify the passed in object (so you would pass by non-const reference) or specifically wanting a copy made (a common operator= technique uses this) or allowing a null argument to be passed in (where you would use a pointer).