2. const member functions #
Created Saturday 11 January 2020
What is const in OOP? #
- A
const
object - an object whose data-members are all const. This is by definition. - A
const
member function is a member function that guarantees it will not modify the object or call any non-const member functions (as they may modify the object).
How to make a function ‘const’ #
- If our const mark(on the function) is fake(i.e it changes the object), then the const binding of the data member will be give an error.
- How to tag a function as const. Put const after the parentheses, before the definition code block.
class A
{
...
void foo() const
{
// code
}
...
};
Note
- Const functions can be invoked through both const and non const objects.
- Const objects can access only const functions, i.e const objects are limited in their actions.
- A const function can change attributes for a non-const param passed to it. The only restriction is changing the caller object.
- Special functions(like constructors, destructor and copy assignment operator) cannot be made
const
. - A function can be overloaded to have a
const
function and a non-const
, both are considered different, because constness is part of the function signature. Here aconst
object will call theconst
function, otherwise the normal function is called.
How does const work #
const functions just have a** const T* instead of a normal this. **
Changing a data structures in a const function #
Why use as constant functions?: https://en.wikibooks.org/wiki/C%2B%2B_Programming/Programming_Languages/C%2B%2B/Code/Keywords/return
- Remember const first takes value then tags the path constant.