Download presentation
Presentation is loading. Please wait.
1
const in Classes CSCE 121 J. Michael Moore
2
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’
3
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.
4
Making things const Any method that does not change something in the class. Any getter/accessor. Add to function declaration and definition.
5
getMyAttr() is not a const function
What it looks like class MyClass { int myAttr = 7; public: // ... MyClass(int k) : myAttr(k) {} int getMyAttr(); }; int MyClass::getMyAttr() { return myAttr; } int operator+(const MyClass& a, const MyClass& b) { return a.getMyAttr() + b.getMyAttr(); } Compiler error! a & b passed by const ref. getMyAttr() is not a const function
6
getMyAttr() is a const function
What it looks like class MyClass { int myAttr = 7; public: // ... MyClass(int k) : myAttr(k) {} int getMyAttr() const; }; int MyClass::getMyAttr() const { return myAttr; } int operator+(const MyClass& a, const MyClass& b) { return a.getMyAttr() + b.getMyAttr(); } a & b passed by const ref. getMyAttr() is a const function OK!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.