Hi, are there other ways of calling a const/non-const override? I want to defined some functions in terms of others, particularly accessors which might or might not require constness- in order to not copy & paste code. This is my current solution:
Your code is backwards - the non-const version should call the const version. Right now, you have the const version calling the non-const version, and you're using a very dangerous const-cast when you don't know for a fact that you're allowed to.
Generally though you don't need a non-const version if you need a const version (though in this case of course you do need both).
Ugh, my mistake. I had done something along the lines of what you two have suggested, but I got an infinite loop, and then changed my code to what I have posted in my first post, which worked.
Thanks for the pointer- I find these sort of things so easy to overlook.
Edit:
JLBorges- that isn't what I want to do. What I want is for either the const or non-const overload to call the other. What you posted doesn't do that.
LB: Can you post an example of how to do what you described? I agree that I'd rather the non-const call the const overload, but I'm not sure on the exact syntax of how to do that.
I know, but it doesnt do what I want it to. The idea is to have one of the overloads call the other, so that I dont need to duplicate the code. Obviously in this example its rather pointless, but this is just an example. What he has is just a duplicated function, one with, and one without constness. What I want is to have the const version return the non-const version.
1 2 3 4 5 6 7 8
constint& dumbArray::operator[](unsignedint _index) const {
std::cout << "dumbArray const operator[] called" << std::endl;
return (*this)[_index]; // I want this to call the non-const overload, seen below.
}
int& dumbArray::operator[](unsignedint _index){
std::cout << "dumbArray non-const operator[] called" << std::endl;
return m_array[_index];
}
Without a const-cast, for the reasons you said in your first post LB
I think there is some misunderstanding here - jaded7 wants "to have the const version return the non-const version", but this doesn't make sense. Can we have some clarification?
For operator[] with usual semantics, non-const overload doesn't modify the state of *this, it only provides a reference that others may use to modify it, so const_cast is actually considered to be justified (e.g. by Scott Meyers) in this case if code reuse is needed.. but as JLBorges pointed out, duplicate code is much simpler in this case.
(but returning constint& seems silly to me: what kind of member functions you're expecting the caller to invoke in the returned lvalue? Just return int)