Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,890 questions

51,819 answers

573 users

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
...