Re: What is polymorphism?
Seigfried wrote:
I have to write a paper about object oriented programming and I'm doing
some reading to make sure I understand it. In a book I'm reading,
however, polymorphism is defined as:
"the ability of two different objects to respond to the same request
message in their own unique way"
I thought that it was:
"the ability of same object to respond to different messages in
unique ways"
That is procedural programming. Witness:
struct Foo { ... };
void Bar(Foo * pFoo, int q);
void Baz(Foo * pFoo, double n);
Bar() and Baz(), conceptually, are methods of Foo. The calling syntax,
Bar(pFoo, 42), is irrelevant. pFoo->Bar(42) would be syntactic sugar.
So here Foo responds to the Bar "message" differently than it responds to
the Baz() "message".
Now consider (in a hypothetical C-like language):
struct Frob { ... };
struct Glob: Frob { ... };
void Bar(Frob * pFrob, int q);
void Bar(Glob * pGlob, int q);
Glob aGlob;
Frob * pFrob = &aGlob;
Bar(pFrob, 42);
Each version of Bar() does something different. One works on Frobs, the
other on Globs. However, in this magical language, the Bar message does
not bind to a Bar method at compile time. That means the compiler does
not look at Bar(pFrob, 42), see only a Frob* type, and pick void Bar(Frob
* pFrob, int q).
Instead, the compiler adds extra code that waits until runtime. That code
detects that pFrob* reeeeally points to a Glob. So at runtime the code
around Bar(pFrob, 42) can remain oblivious to the correct type. That saves
the code from a lot of tangled 'if' statements detecting things true types.
So in C++:
Frob & aFrob = getObject();
aFrob.Bar(42);
The dot . knows which Bar() to pick, at runtime.
The examples in the book that follow seem to support my understanding.
Is this an error in the book or am I not understanding it?
Report the book's name here, and reveal one of the examples, and read
/Design Patterns/ before you finish this paper. It shows polymorphism in
use, solving real problems, unlike some books we could mention...
--
Phlip