473,379 Members | 1,252 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,379 software developers and data experts.

What is polymorphism?

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
18 3827
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
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
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

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
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
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

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
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
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
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

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
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
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
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

37
by: Mike Meng | last post by:
hi all, I'm a newbie Python programmer with a C++ brain inside. I have a lightweight framework in which I design a base class and expect user to extend. In other part of the framework, I heavily...
18
by: Ken | last post by:
Hi. Can anyone refer me to any articles about the compatibility between c++ polymorphism and real-time programming? I'm currently on a real-time c++ project, and we're having a discussion...
10
by: Danny Ni | last post by:
Hi, I was asked a question in a recent interview, where in ASP.Net is polymorphism used? I got differrent answers from different people, One said ToString() method because it is working for...
35
by: JKop | last post by:
http://msdn.microsoft.com/library/default.asp?url=/library/en- us/vccore98/HTML/_core_using_strict_type_checking.asp Pay particular attention to: The types WPARAM, LPARAM, LRESULT, and void *...
19
by: G.Ashok | last post by:
Hi All, What is your weightage of the 3 characteristics of Object-Oriented Programming i.e. Inheritance, Encapsulation and Polymorphism. for a total of 100% Please quote your values and let's...
6
by: John Salerno | last post by:
I understand how they work (basically), but I think maybe the examples I'm reading are too elementary to really show their value. Here's one from Programming C#: #region Using directives ...
2
by: sarathy | last post by:
Hi all, I need a small clarification reg. Templates and Polymorphism. I believe templates is really a good feature, which can be used to implement generic functions and classes. But i doubt...
10
by: vb.here | last post by:
Hi all, I am new to C++ and was just reading about polymorphism. I tried to write a very simple program. Then a curious thought came into my mind. And instead of using pointer in polymorphism, i...
123
by: plenty900 | last post by:
I was looking over someone's C++ code today and despite having written perfectly readable C++ code myself, the stuff I was looking at was worse than legalese. The people who are guiding the...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.