void foo(const ClassName &name)
{
...
}
How can I access the method of class instance name?
name.method() didn’t work. then I tried:
void foo(const ClassName &name)
{
ClassName temp = name;
... ....
}
I can use temp.method, but after foo was executed, the original name screwed up, any idea?
BTW, the member variable of name didn’t screwed up, but it was the member variable of subclass of class screwed up.
If I understand you correctly, you want to call
name.method()insidefoo()and the compiler doesn’t let you. IsClassName::method()a non-const method by any chance? Sincenameis declared as aconstparameter tofoo(), you can only callconstfunctions on it.Update: if
ClassName::method()is non-const, but does not actually change state, the best would be of course to make itconst. In case you can’t for some reason, I see the following ways:nameas a non-const method parameter.name, and callmethodon it – as you actually did. However, this works only if the assignment operator and/or copy constructor is properly implemented forClassName. However, you write “after foo was executed, the original name screwed up”, which is a very vague description, but it can be interpreted so that copying did have some unwanted side effects onname, which suggests that those functions are not implemented correctly or at all.const_cast– this should really be a last resort, and only if you are sure thatClassName::method()does not actually change any state.Update2, to @AKN’s comment – example of casting away constness: