How to change a variable in method that marked as const in C++

1 Answer

0 votes
#include <iostream>

class Example {
private:
    int m_X, m_Y;
    mutable int m_Z; // mutable allows changing a variable in method const 
public:
    Example() {
        m_X = 3;
        m_Y = 8;
    }

    int GetZ() const {
        m_Z = 9;
        
        return m_Z;
    }
};

void Print(const Example& ex) {
    std::cout << ex.GetZ();
}
 
int main() {
    Example ex;
    
    Print(ex);
}
 
 
 
 
/*
run:
 
9
 
*/

 



answered Feb 1, 2023 by avibootz

Related questions

...