Will this syntax avoid virtual calls?

Started by
11 comments, last by dmatter 16 years, 1 month ago
Quote:Original post by ToohrVyk
Quote:Original post by Ashkan
Besides, we definitely don't need runtime polymorphism here since we exactly know what implementation of the interface we need: the one that we are currently implementing.


No, you don't. You know that the implementation you need inherits from the one you are currently implementing.

As it stands, someone could inherit from Derived and change the behavior of the F function. For instance, using a multimap-like container to implement a map-like container where binding a key to a new value hides the old binding of that key until the new binding is removed—the old bindings are still being stored, but they do not count against the container's size nor do they appear in iterations.

If your function g assumes that Derived::F computes the number of elements in the container, then this assumption will be wrong and you will get strange behavior as a result.


Yes, I now see the point you guys are making, which makes me wonder what the correct solution is. Should I factor the common code into a third function which is used by both F() and g()?

Quote:
Quote:Original post by Ashkan
A more verbose approach is to factor the common code in another function and use that in both F() and g().


This new function should probably be virtual for the same reason that F() is virtual now.


But this design is also prone to the same set of problems. What if this third virtual function is overridden in classes Derived from this class?!
Advertisement
Show real code for a real example of what you're doing. Otherwise there's no point in giving design advice for what to do.
Quote:Original post by Ashkan
Yes, I now see the point you guys are making, which makes me wonder what the correct solution is. Should I factor the common code into a third function which is used by both F() and g()?

If there is common code then refactoring is, typically, a good idea anyway.

As for a correct solution, it sounds like you want runtime polymorphism but without the overhead, which just isn't do-able. The solution would be to call the virtual function normally, with vtable lookup and everything.

Quote:
Quote:
This new function should probably be virtual for the same reason that F() is virtual now.


But this design is also prone to the same set of problems. What if this third virtual function is overridden in classes Derived from this class?!

Oh, I didn't mean for you to statically call this function as you're right it would suffer the same problems if this was the case. I was expecting you to make a runtime polymorphic call to it. [smile]

If you can provide more context to your actual problem then there might be a statically bound solution, although I presume based on your previous posts that you've ruled out a totally-at-compile-time static polymorphic approach?

This topic is closed to new replies.

Advertisement