How to declaring a member function as read-only function with the const keyword in C++

1 Answer

0 votes
// f() const - this function/method cannot change any of the object members in which it is called. 
// It's a non-mutable member function
 
#include <iostream>
  
class Example {
    private: 
        int num = 34;
    public:
        Example() {};
        void change() {
            num = 17;
        }
        void cannotchange() const {
            // num = 100; // error: assignment of member 'Example::num' in read-only object
        }
        void print() {
            std::cout << num << "\n";
        }
        
};
      
 
int main() {
    Example obj;
      
    obj.change();
    obj.print();
}

    
    
/*
run:
    
17
    
*/

 



answered Sep 16, 2024 by avibootz
edited Sep 16, 2024 by avibootz

Related questions

1 answer 208 views
1 answer 222 views
1 answer 124 views
1 answer 122 views
1 answer 227 views
...