Polymorphism design

  • Thread starter Thread starter Chris Capel
  • Start date Start date
C

Chris Capel

When is it appropriate to use virtual functions, and when more appropriate
to use interfaces? Of course, there are the cases where only a derived class
could have any use for the functions, and there are the cases where the
functions in the interface need to be called on objects in different
inheritence branches, but isn't there a grey area in there? Where to draw
the line?

Chris
 
Others will probably have a better answer than I.

I think of interfaces as methods that unrelated objects need to
implement and use inheritance when the classes are related and can
take advantage of base class functionality.

I don't know that there is a de-facto line that perfectly delineates
when you should use one vs the other. There are probably some best
practices available to help guide you in your design, although I find
experience to be the best teacher overall.

Jonathan Schafer
 
Interfaces are more about discipline.
Let's say there are several teams working on the project. So, in order to
maintain all function signatures the same between teams or developers, you
can force them to use interfaces. In this case, you know that any object
developed by this team or a developer will have fixed function signatures
for commonly used functions, so no one will screw up calling it. Virtual
functions are more about polymorphism. You can have a derived class that
inherits from a base class, but for some functionality, you need different
implementations in the derived class, then you override these functions
leaving the rest the same. There are some classic examples in textbooks, of
course if you care to read them.
 
codewriter said:
Interfaces are more about discipline.
Let's say there are several teams working on the project. So, in order to
maintain all function signatures the same between teams or developers, you
can force them to use interfaces. In this case, you know that any object
developed by this team or a developer will have fixed function signatures
for commonly used functions, so no one will screw up calling it.

I disagree with this. It assumes that people will know the actual type
of object, so that they can call the fixed function signature. In
(good) practice, a lot of things (parameters, return types) should be
specified only by interface where appropriate, so that the actual
implementation type can change at a later date. This is *absolutely*
about polymorphism.
 
Back
Top