What is polymorphism?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Seigfried

    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?

  • mlimber

    #2
    Re: What is polymorphism?

    Seigfried wrote:[color=blue]
    > 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?[/color]

    Your book is right. See these FAQs:



    Cheers! --M

    Comment

    • Seigfried

      #3
      Re: What is polymorphism?

      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:[color=blue]
      > Seigfried wrote:[color=green]
      > > I have to write a paper about object oriented programming and I'm doing
      > > ... <snip> ...[/color]
      > See these FAQs:
      >
      > http://www.parashift.com/c++-faq-lit...functions.html
      >
      > Cheers! --M[/color]

      Comment

      • phlip

        #4
        Re: What is polymorphism?

        Seigfried wrote:
        [color=blue]
        > 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"[/color]

        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.
        [color=blue]
        > 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?[/color]

        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

        Comment

        • BigBrian

          #5
          Re: What is polymorphism?


          Seigfried wrote:[color=blue]
          > 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.[/color]

          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

          Comment

          • Seigfried

            #6
            Re: What is polymorphism?

            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:[color=blue]
            > Seigfried wrote:[color=green]
            > > 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.[/color]
            >
            > 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[/color]

            Comment

            • mlimber

              #7
              Re: What is polymorphism?

              Seigfried wrote:[color=blue]
              > 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?"[/color]

              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

              Comment

              • BigBrian

                #8
                Re: What is polymorphism?


                Seigfried wrote:[color=blue]
                > OK ... got that too. (And, again, thanks for the reply.)
                >[/color]

                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, "polymorphi sm" 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.
                [color=blue]
                > 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?"[/color]

                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

                Comment

                • Marcus Kwok

                  #9
                  Re: What is polymorphism?

                  Seigfried <Seigfried@msn. com> wrote:[color=blue]
                  > 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"[/color]

                  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();
                  [color=blue]
                  > I thought that it was:
                  >
                  > "the ability of same object to respond to different messages in
                  > unique ways"[/color]

                  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".
                  [color=blue]
                  > 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?[/color]

                  --
                  Marcus Kwok
                  Replace 'invalid' with 'net' to reply

                  Comment

                  • Seigfried

                    #10
                    Re: What is polymorphism?

                    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 "polymophis m" 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:[color=blue]
                    > That is procedural programming. Witness:
                    >
                    > ... <snip>[/color]

                    Comment

                    • mlimber

                      #11
                      Re: What is polymorphism?

                      Seigfried wrote:[color=blue]
                      > 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.[/color]

                      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

                      Comment

                      • Seigfried

                        #12
                        Re: What is polymorphism?


                        Seigfried wrote:[color=blue]
                        > 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?[/color]

                        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.

                        Comment

                        • Erik Wikström

                          #13
                          Re: What is polymorphism?

                          On 2006-06-06 19:39, Seigfried wrote:
                          [...][color=blue]
                          > "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 "polymophis m" was "same name - different SIGNATURE -
                          > different methods" - not "different names". This was the crux of my
                          > question.[/color]

                          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

                          Comment

                          • Marcus Kwok

                            #14
                            Re: What is polymorphism?

                            Seigfried <Seigfried@msn. com> wrote:[color=blue]
                            > 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."[/color]
                            [...][color=blue]
                            > "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 "polymophis m" was "same name - different SIGNATURE -
                            > different methods" - not "different names". This was the crux of my
                            > question.[/color]

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

                            --
                            Marcus Kwok
                            Replace 'invalid' with 'net' to reply

                            Comment

                            • mlimber

                              #15
                              Re: What is polymorphism?

                              Seigfried wrote:[color=blue]
                              > 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.[/color]

                              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

                              Comment

                              Working...