How to prevent a method to modify the class member variables in C++

1 Answer

0 votes
#include <iostream>

class Example {
private:
    int m_X, m_Y;
public:
    void Test(void) const { // const prevent a method to modify the variables 
        m_X = 3;
        m_Y = 8;
    }
};
 
int main() {
   Example ex;
   
   ex.Test();
}
 
 
 
 
/*
run:
 
error: assignment of member ‘Example::m_X’ in read-only object
error: assignment of member ‘Example::m_Y’ in read-only object
 
*/

 



answered Feb 1, 2023 by avibootz
...