By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,665 Members | 1,912 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,665 IT Pros & Developers. It's quick & easy.

What is polymorphism?

P: n/a
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"

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?

Jun 6 '06 #1
Share this Question
Share on Google+
18 Replies


P: n/a
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"

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?


Your book is right. See these FAQs:

http://www.parashift.com/c++-faq-lit...functions.html

Cheers! --M

Jun 6 '06 #2

P: n/a
OK ... I get the "static typing" versus "dynamic typing" (the only
reference to polymorphism in your link) but I don't think that answers
the question. It seems to me that the way the invoked function is
selected remains a different signature (that is, in the language of the
book, "request message"). The only thing that your reference seems to
demonstrate is that it's possible for an invoked function to, in turn,
invoke another function. In logical terms, this can be thought of as
simply two ways of invoking the same function.

I don't want to seem ungrateful, but it's awfully common for people to
simply respond to questions with "see this link ... it explains
everything". What I'm looking for is WHY does this link "explain
everything".

mlimber wrote:
Seigfried wrote:
I have to write a paper about object oriented programming and I'm doing
... <snip> ...

See these FAQs:

http://www.parashift.com/c++-faq-lit...functions.html

Cheers! --M


Jun 6 '06 #3

P: n/a
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
Jun 6 '06 #4

P: n/a

Seigfried wrote:
OK ... I get the "static typing" versus "dynamic typing" (the only
reference to polymorphism in your link) but I don't think that answers
the question.


Dynamic typing, through virtual functions, is how C++ implemented
runtime polymorphism. Runtime polymorphism is the ability at run time
to determine what (derived) type a pointer points to and call the
appropriate (virtual) method.

-Brian

Jun 6 '06 #5

P: n/a
OK ... got that too. (And, again, thanks for the reply.)

But the specific details of C++ runtime implementation of polymorphism
wasn't the question. The question was, "The book seems wrong to me -
what do you think?"

BigBrian wrote:
Seigfried wrote:
OK ... I get the "static typing" versus "dynamic typing" (the only
reference to polymorphism in your link) but I don't think that answers
the question.


Dynamic typing, through virtual functions, is how C++ implemented
runtime polymorphism. Runtime polymorphism is the ability at run time
to determine what (derived) type a pointer points to and call the
appropriate (virtual) method.

-Brian


Jun 6 '06 #6

P: n/a
Seigfried wrote:
But the specific details of C++ runtime implementation of polymorphism
wasn't the question. The question was, "The book seems wrong to me -
what do you think?"


Don't top post. It's considered rude here.

The book is right. C++ implements run-time (or dynamic) polymorphism
through the virtual function mechanism. For instance:

#include <iostream>

struct Foo
{
virtual void Message() const { std::cout << "Foo::Message()\n"; }
};

struct Bar : Foo
{
virtual void Message() const { std::cout << "Bar::Message()\n"; }
};

void CallMessage( const Foo& foo )
{
foo.Message(); // This is the key line
}

int main()
{
Foo foo;
Bar bar;
CallMessage( foo );
CallMessage( bar );
}

Note that CallMessage() accepts a reference (it could just as well
accept a pointer, but not an object). That function requests that the
object of type Foo (or a derived type thereof) print its message. Any
object in the hierarchy based at Foo can be passed into that function,
but each can respond to the "message" (i.e. function call) differently
thanks to the virtual function mechanism in C++. This is just what your
book said: Foo and Bar are different (though related) objects that
respond differently to the same message (i.e., invocation of the
virtual function Message()).

Cheers! --M

Jun 6 '06 #7

P: n/a

Seigfried wrote:
OK ... got that too. (And, again, thanks for the reply.)

Your message subject is "What is polymorphism?" so I supplied my own
definition. Your original post said that the definition in question
was...

"the ability of two different objects to respond to the same request
message in their own unique way"

In general, I would agree with this definition.

However, usually by itself, "polymorphism" refers to "runtime
polymorphism" ( at least that's how people that I work with use the
term ). However, since some people also use the term "compile time
polymorphism", I think it's important for the definition to include
something about the fact that the decision as to which function to call
happens at runtime.
But the specific details of C++ runtime implementation of polymorphism
wasn't the question. The question was, "The book seems wrong to me -
what do you think?"


I would say that your book gave a very general definition of
polymorphism. Since this newsgroup deals with C++, I was inclined to
include something about virtual functions in my definition.

-Brian

Jun 6 '06 #8

P: n/a
Seigfried <Se*******@msn.com> 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 am not quite sure what you mean by "request message", but in this
context I am assuming you mean a function call.

For example, I'll use the canonical polymorphism example of shapes.

Suppose we have an abstract class Shape:

class Shape {
public:
// pure virtual function has no implementation and must be
// overridden by derived classes, since there is not really a
// generic algorithm to draw an arbitrary shape
virtual void draw() = 0;

// virtual destructor is needed so that derived classes will be
// destroyed correctly when being deleted through a base class
// pointer
virtual ~Shape() { }
};

Then we have concrete specific shapes:

class Square : public Shape {
public:
virtual void draw() { /* draw a square */ }
};

class Circle : public Shape {
public:
virtual void draw() { /* draw a circle */ }
};

Then, we can instantiate two different objects, and they will respond to
the same request (draw) in their own unique way:

Shape& s = Square();
Shape& c = Circle();

// Draw a square
s.draw();

// Draw a circle
c.draw();
I thought that it was:

"the ability of same object to respond to different messages in
unique ways"
I would interpret this more like function overloading, but see below.

class Drawer {
public:
void draw(Square s) { /* draw a square */ }
void draw(Circle c) { /* draw a circle */ }
};

Drawer d;
Square s;
Circle c;

// Draw a square
d.draw(s);

// Draw a circle
d.draw(c);

However, this has the drawback (no pun intended) that the Drawer class
must know how to draw each kind of shape. If you decide to make a new
shape (e.g., Triangle), then you also need to update the Drawer class.

However, using polymorphism as described from the first example, we
could reimplement the Drawer class as such:

class Drawer {
public:
void draw(Shape& s) { s.draw(); }
};

All classes that derive from Shape must implement the draw() function,
so the above will work. Since draw() is virtual and we are calling it
through a reference (or a pointer), then the virtual dispatch mechanism
will kick in, and the draw() function that actually gets executed will
depend on the specific type of Shape that it is at run-time.

Drawer d;
Square s;
Circle c;

// Draw a square
d.draw(s);

// Draw a circle
d.draw(c);

Now, when we create the new Triangle type, we just have to implement
Triangle's draw() function, and it will work with the existing Drawer
class with no changes needed.

I am guessing that this last example could be interpreted as "the same
object responding to different messages in unique ways".
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?


--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Jun 6 '06 #9

P: n/a
Whew! When I asked, "WHY does this link explain everything," I should
have remembered that one should always be careful about what one asks
for. I'm also reminded that "42" is the ultimate answer to "Life, the
Universe, and Everything." I presume that's why you used it in your
reply.

After reading your message several times, I believe you said, "the book
is not correct" ... but I could be wrong about that. The concern about
misinterpreting something and reaching an incorrect conclusion was why
I wrote my question in the first place. You have certainly given me
much, much more to potentially misinterpret.

Anyway ... the book I'm reading is written at a FAR higher conceptual
level. Here's the an example from the book. (This REALLY IS directly
quoted.)

"I could train my dog to respond to the command 'bark' and my bird to
respond to the command 'chirp.' On the other hand, I could train them
to both respond to the command "speak." Through polymorphism, I know
that the dog will respond with a bark and the bird will respond with a
chirp."

Not quite C++ syntax, but we're dealing with concepts here.

Just a few paragraphs further on, the same book states:

"In OOP, you implement this type of polymorphism through a process
called overloading. You can implement different methods of an object
that have the same name."

comment:

Yeah ... but "bird and "dog" are DIFFERENT names. Of course you can
call different objects and get different results. I thought the key
concept behind "polymophism" was "same name - different SIGNATURE -
different methods" - not "different names". This was the crux of my
question.

But - this discussion has been very helpful. My conclusion now is that
the error in the book is not an actual error of fact, it's just writing
that is generalized to such a high level that it misses the main point.

Thanks again.

ps ... I have several books named "Design Patterns." (I'm a real book
junkie.) Hopefully, I'll be able to understand them better in the
future as a result of understanding these fundamental concepts now.

phlip wrote:
That is procedural programming. Witness:

... <snip>


Jun 6 '06 #10

P: n/a
Seigfried wrote:
My conclusion now is that
the error in the book is not an actual error of fact, it's just writing
that is generalized to such a high level that it misses the main point.


No. The book uses different terminology that C++ folk do, but the
concept is the same. I'm afraid to say that it is you who have missed
the main point.

Cheers! --M

Jun 6 '06 #11

P: n/a

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"

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?


I'd like to sincerely thank all of you who responded. I have read all
of the messages and I think I now understand what the book was trying
to communicate (although I think the author could have written it much
more clearly and avoided a lot of confusion).

To the poster who suggested that I not "top post" because it is
considered rude, I apologize for violating that poster's grammatical
shibboleth. I'm not entirely sure what "top post" means but my only
intent was to communicate as clearly as possible.

Jun 6 '06 #12

P: n/a
On 2006-06-06 19:39, Seigfried wrote:
[...]
"I could train my dog to respond to the command 'bark' and my bird to
respond to the command 'chirp.' On the other hand, I could train them
to both respond to the command "speak." Through polymorphism, I know
that the dog will respond with a bark and the bird will respond with a
chirp."

Not quite C++ syntax, but we're dealing with concepts here.

Just a few paragraphs further on, the same book states:

"In OOP, you implement this type of polymorphism through a process
called overloading. You can implement different methods of an object
that have the same name."

comment:

Yeah ... but "bird and "dog" are DIFFERENT names. Of course you can
call different objects and get different results. I thought the key
concept behind "polymophism" was "same name - different SIGNATURE -
different methods" - not "different names". This was the crux of my
question.


Try to think of it like this, there is a class called Animal which has a
method called speak(). Dog and Bird are both derived from Animal and
thus both have the method speak(), but they overload this method with a
version appropriate for whatever kind of animal they are.

Thus when the command speak is given it is not given to the dog, it is
given to an animal, and that animal then uses it's own implementation of
speak. This is the "same name"-thing you are talking about. You don't
need to know if it's a dog or a bird, just that it's an animal and that
an animal can perform certain tasks.

Erik Wikström
--
"I have always wished for my computer to be as easy to use as my
telephone; my wish has come true because I can no longer figure
out how to use my telephone" -- Bjarne Stroustrup
Jun 6 '06 #13

P: n/a
Seigfried <Se*******@msn.com> wrote:
Anyway ... the book I'm reading is written at a FAR higher conceptual
level. Here's the an example from the book. (This REALLY IS directly
quoted.)

"I could train my dog to respond to the command 'bark' and my bird to
respond to the command 'chirp.' On the other hand, I could train them
to both respond to the command "speak." Through polymorphism, I know
that the dog will respond with a bark and the bird will respond with a
chirp." [...] "In OOP, you implement this type of polymorphism through a process
called overloading. You can implement different methods of an object
that have the same name."

comment:

Yeah ... but "bird and "dog" are DIFFERENT names. Of course you can
call different objects and get different results. I thought the key
concept behind "polymophism" was "same name - different SIGNATURE -
different methods" - not "different names". This was the crux of my
question.


I think the point is that both "bird" and "dog" have a common "speak"
method.

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Jun 6 '06 #14

P: n/a
Seigfried wrote:
To the poster who suggested that I not "top post" because it is
considered rude, I apologize for violating that poster's grammatical
shibboleth. I'm not entirely sure what "top post" means but my only
intent was to communicate as clearly as possible.


It was neither grammatical it nature, a shibboleth, nor mine alone. It
refers to the way in which one quotes the post s/he is responding to,
and you'll note that the common practice by all who responded to you
(not just me) was to put their comments *below* the part of your
message which they were responding to. It just makes the conversation
easier to follow.

Cheers! --M

Jun 6 '06 #15

P: n/a
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"

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?


I suspect you are not understanding it.

I have a slightly different emphasis. Polymorphism is when
different objects have the same interface, or share some
portion of their interface in common. That is, they can take
the same message, or some set of messages, in common.

The easiest example of polymorphism is the electric outlet
commonly found in a house. You can stick many different
kinds of device into that plug. Even devices that were invented
after the outlet was installed. You've got one interface, and
you can attach many different objects to it, and they each
do their own job as a result. Hair dryers, chargers for cell
phones, electric train sets, they all have this same interface.
At least that part of it.

Similarly, you can have different kinds of outlets, and plug
different objects into them. Even when the object was produced,
and you bought it, before the outlet was produced. Regular wall
outlets, simple extension cords, power bars with those keen
little orange lights that flicker all the time, uninteruptable power
(don't interupt) supplies. They all have those same three little
holes you can stick things into, and as long as everybody
obeys the interface rules, all is well.

So too with software. You've got some interface in your
code (the message) and different objects, even different types
of objects, can be plugged into it. And they can do their own
task when the interface sends them a message. And different
types of objects can send the message.
Socks

Jun 6 '06 #16

P: n/a
I have a slightly different emphasis. Polymorphism is when
different objects have the same interface, or share some
portion of their interface in common. That is, they can take
the same message, or some set of messages, in common.


99% of c++ programmers that I know use the term "polymorphism" to
really mean "runtime polymorphism". Given this assumption, I could see
what you say as confusing to somebody trying to learn about runtime
polymorphism. Objects which share the same interface can be used in a
template ( for compile time polymorphism ), but without inheritance and
virtual functions, (runtime) polymorphism doesn't happen.

-Brian

Jun 6 '06 #17

P: n/a
BigBrian wrote:
I have a slightly different emphasis. Polymorphism is when
different objects have the same interface, or share some
portion of their interface in common. That is, they can take
the same message, or some set of messages, in common.


99% of c++ programmers that I know use the term "polymorphism" to
really mean "runtime polymorphism".


Agreed, but there is technically more to the concept than that, and if
you search the archives for this group, you'll see plenty of references
to templates as "static polymorphism."

Cheers! --M

Jun 7 '06 #18

P: n/a
BigBrian wrote:
I have a slightly different emphasis. Polymorphism is when
different objects have the same interface, or share some
portion of their interface in common. That is, they can take
the same message, or some set of messages, in common.


99% of c++ programmers that I know use the term "polymorphism" to
really mean "runtime polymorphism". Given this assumption, I could see
what you say as confusing to somebody trying to learn about runtime
polymorphism. Objects which share the same interface can be used in a
template ( for compile time polymorphism ), but without inheritance and
virtual functions, (runtime) polymorphism doesn't happen.


Inheritance and virtual functions are one path to producing
polymorphism. Basically, they are one way of getting two or
more classes with some portion of their interface in common.

However, as others have said, there are other paths to the
same notion. The notion of polymorphism and the way it is
commonly done in C++ shouldn't be seen as identical.

Templates have already been mentioned.

There are also factory methods, for example. You give a class
that is to interact with a factory the methods the factory needs.
Such as a named constructor, often with a fixed name like
"FactoryConstructor()" or some such. Then the factory object
can make instances of classes that are written long after the
factory object is written. Or, a new version of the factory could
be written, and accomodate classes that were written already.

The fundamental notion of polymorphism is the interface and
how different objects can be on either side of it without the
other side caring. And of course it leads nicely into the other
concepts of OOD and OOP, like information hiding,
encapsulation, abstract data types, etc.
Socks

Jun 7 '06 #19

This discussion thread is closed

Replies have been disabled for this discussion.