Quote:
Original post by direwulf
Quote:
Original post by Lode
I've got to write the same "complex recursive code" twice. Twice exactly the same. But I couldn't find any way to write the one function in terms of the other or vica versa.
Is there a way to avoid code duplication?
Instead of making "complex recursive code" a function that returns a const or non-const pointer, make it a function that returns void..and return the const or non-const pointer separately. Then it can be used in both functions.
I can't actually think of any sensible reason why you should want to do this, and it makes me think that it may just be a result of bad design.
Also it's more usual to return a const-reference, rather than const-pointer.
The use is:
hitTest tests if the mouse hits an element. An element can have smaller sub-elements in it. The return value can be the element itself (this), or a pointer to one of the sub elements (if the mouse is over those). Each sub element itself can again have its own sub elements and so on.
Not only is a single function being duplicated, but it's virtual and all different types of elements would have to override twice and do twice the same in it.
It's not possible to return a non const pointer to this from a const member function, and sometimes the hit test is needed in a const case where a const return value is OK, in other cases the hit test is needed for something where you have a non const reference to the object and you also need a non const result from the hit test.
For example, when drawing it, a const one is enough, you just need to get some coordinates from it to draw something on the screen. When editing it with the mouse, you need a non const one, that is modifiable.
Also, I've seen both references and pointers returned for various things in various situations, but I think the advantage of using a pointer, is that you can return "0" if needed to represent "nothing".
In which of his books exactly does Scott Meyer write about this legitimate use of const_cast? I tried to find it with google and did find a thread somewhere else similar to this one where something similar from Scott Meyer is referenced, but not the exact source. I'm interested in it :)
[Edited by - Lode on October 13, 2009 6:55:41 AM]