const in Classes CSCE 121 Recall Pass by
const in Classes CSCE 121
Recall – Pass by constant reference • Guarantees that memory pointed to is not modified • How? • Classes have methods / member functions that may or may not modify the instance of the class. • Compiler only allows methods to run that are identified to NOT change the class. • Label with ‘const’
So far • When doing most types of operator overloading, we should not change the values of the parameters passed in. • Skirted the issue by passing by reference instead of by constant reference. • NOT GOOD PRACTICE • When passing in objects of any type into a function that should not be changed, pass by constant reference.
Making things const • Any method that does not change something in the class. • Any getter/accessor. • Add to function declaration and definition.
What it looks like class My. Class { Com a int my. Attr = 7; & g e public: t. My b pas piler e rror Attr sed //. . . () is by c ! My. Class(int k) : my. Attr(k) {} not ons int get. My. Attr(); a co t ref }; . n int My. Class: : get. My. Attr() { return my. Attr; } int operator+(const My. Class& a, const My. Class& b) { return a. get. My. Attr() + b. get. My. Attr(); } st fu ncti on
What it looks like class My. Class { int my. Attr = 7; public: //. . . My. Class(int k) : my. Attr(k) {} int get. My. Attr() const; }; int My. Class: : get. My. Attr() const { a& get. M b pa OK! y. At ssed by c tr() is a ons t re con st fu f. ncti on return my. Attr; } int operator+(const My. Class& a, const My. Class& b) { return a. get. My. Attr() + b. get. My. Attr(); }
- Slides: 6