If I understand you correctly, you want to call name.method() inside foo() , and the compiler does not allow you. Is ClassName::method() non-constant method? Since name declared as a const parameter to foo() , you can call const functions on it.
Update: if ClassName::method() not a constant, but does not actually change the state, it would be best, of course, to make it const . If you cannot for some reason, I see the following ways:
- (the obvious way, as @Naveen pointed out - thanks :-) to declare
name as a parameter of a non-constant method. - create a non-constant copy of
name and call method on it - as you did. However, this only works if the assignment operator and / or copy constructor are correctly implemented for ClassName . However, you write "after foo was executed, the original name is screwed on", which is a very vague description, but it can be interpreted so that copying does have some unwanted side effects on name , which suggests that these functions do not are implemented correctly or in general. - (disgusting way) discards a constant using
const_cast - this really should be the last resort, and only if you are sure that ClassName::method() does not actually change any state.
Update2 , to the comment @AKN - an example of a constant deviation:
void foo(const ClassName &name) { ClassName& temp = const_cast<ClassName&>(name); ... .... }
source share