On Mon, Apr 22, 2013 at 12:37:09PM -0600, Owen Densmore wrote:
> 
> In duck typing, one is concerned with just those aspects of an object that
> are used, rather than with the type of the object itself. For example, in a
> non-duck-typed language, one can create a function that takes an object of
> type Duck and calls that object's walk and quack methods. In a duck-typed
> language, the equivalent function would take an object of any type and call
> that object's walk and quack methods. If the object does not have the
> methods that are called then the function signals a run-time error. If the
> object does have the methods, then they are executed no matter the type of
> the object, evoking the quotation and hence the name of this form of typing.
> Duck typing is aided by habitually *not* testing for the type of arguments
> in method and function bodies, relying on documentation, clear code and
> testing to ensure correct use.

In C++, generic programming, or static polymorphism, is often called
duck-typing. If my generic algorithm expexcts the object passed to it
have walk, quack and swim methods, then the compiler will not allow
you to pass in something that doesn't have those methods, but otherwise
there are no other restrictions on the object passed in.

This is in contrast to dynamic polymorphism, which is like Java's - the
object you pass in must inherit from a base class, which becomes part
of the documented interface of the method. "You are only allowed to
pass in ducks here, but I don't care what species they are." Side note
- Java has "generics", but you can't really do "generic programming",
or "duck-typing" in Java, AFAICT.

Obviously, in more dynamic languages like Javascript, duck-typing
errors must be caught at run time, but in static languages like C++,
they are caught at compile time.

Cheers
 --

----------------------------------------------------------------------------
Prof Russell Standish                  Phone 0425 253119 (mobile)
Principal, High Performance Coders
Visiting Professor of Mathematics      hpco...@hpcoders.com.au
University of New South Wales          http://www.hpcoders.com.au
----------------------------------------------------------------------------

============================================================
FRIAM Applied Complexity Group listserv
Meets Fridays 9a-11:30 at cafe at St. John's College
to unsubscribe http://redfish.com/mailman/listinfo/friam_redfish.com

Reply via email to