Maybe it's better to show the code then it is better to understand what my problem is.
Class:
Cls::Cls() {}
Cls::Cls(int &var) : m_var(var){
std::cout << "constructor: " << m_var << std::endl;
}
Cls::~Cls() {}
void Cls::setVar() const {
m_var = 5;
std::cout << "setVar: " << m_var << std::endl;
}
Header:
class Cls {
public:
Cls();
Cls(int &var);
virtual ~Cls();
void setVar() const;
private:
mutable int m_var;
};
The main:
int main() {
int var = 1;
Cls *cls;
cls = new Cls(var);
cls->setVar();
std::cout << "var: " << var << std::endl;
}
So, I passed var
using the custom constructor Cls(int &var)
. After it, I call a function changing the value of the variable. I expected, that I would see the change in the main
. I was wrong. How can I achieve that? I don't want to pass the variable as function argument.