Polymorphism?

Pages: 12
Can somebody tell me (in a simple way) what polymorphism is?
How does it work?
Any example?

I'm still don't get it (Practically not theoritically).

Thanks in advance.
Consider the following example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

int size(int x);
int size(int a, int b);
int main(){
	cout << "Size of a square with side 5: " << size(5);
	cout << '\n';
	cout << "Size of rectangle of with sides 5,4: " << size(5,4) << endl;
	return 0;
}
int size(int x){
	return (x*x);
}
int size(int a, int b){
	return (a*b);
}


You can actually call the size function but with different arguments. That way you don't have to have different functions for each object you want to find it's size.
The name "polymorphism" means that something has many (poly), forms (morph). So you can have the same thing that does something different according to the situation.
Last edited on
just like template, but I wonder...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Event
{
   public:
   /*abstract*/ void event();
   void doEvent() {
      this.event();
   }
}

class Test : Event
{
   public:
   void event()
   {
        printf("test");
   }
}

int main()
{
    Test t;
    t.doEvent();
}


Is this polymorphism?
Last edited on
Al little different than templates, templates is polymorphism of the same function but with differend type of arguments, not different amount of arguments...

Polymorphism at this example would be to have a pointer at class Event and then change it point to class Test. This would be a polymorphed version of a pointer from a base class to inherited class.
Any other polymorphism thing? Just that?

So, what's the advantages?
Mitsakos That is called function overloading.
http://www.codersource.net/cpp_tutorial_function_overloading.html

Audinue Yes, that is the general idea.
http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming

Templates are neither polymorphic nor overloaded. They are, well, templates.
http://en.wikipedia.org/wiki/Template_%28programming%29
http://www.parashift.com/c++-faq-lite/templates.html

Polymorphism conceptualizes the underpinnings of Object-Oriented design.

Specifically, it is the ability to define an abstract base interface (an ADT) which applies to more than one object. By providing the same interface, different objects may be treated the same way, without having to worry about exactly what kind of thing you are messing with.

For concrete examples
http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming#C.2B.2B
http://www.cplusplus.com/doc/tutorial/polymorphism.html

The advantages are
1) it reduces overhead when handling multiple objects of similar type.
2) it allows new objects to be added to previously written code without modifying the original code.
3) it keeps private stuff private.
4) it is easier to maintain large systems

http://pj.freefaculty.org/Swarm/Beta/SwarmUserGuide/swarm.user.user1.02-obj-adv.sect1.html

Best read:
http://codebetter.com/blogs/raymond.lewallen/archive/2005/02/08/50663.aspx

Hope this helps.
I'm sorry, I thought that overloading is a form of polymorphism...
At least the book I learned everything says that it is overloading but it is a very simple example of polymorphism. The best example would be the class pointer that it is the type of the base and then you can assign it to point at an inherited class.
About templates you can say that they are functions that can accept any kind of data, so they are like having an overloaded function that works for your kind of data, right (or any type of variable, your class, int, char etc)? That automatically create an overloaded function that can handle the kind of data you send them.
Last edited on
In the technical sense of the word it isn't.

But in the idiomatic sense it is... :-)
poly-morph := many-form

That definition is too broad for technical computer terms though... Alas.

The difference is that things like templates and function overloading are resolved at compile-time, but object polymorphism is resolved at run-time. Hence the technical language..
Cool, I didn't know
thanx
I think polymorphism is just someting like Event and RaiseEvent in VB,...

In a simple way, polymorphism is a callback inside a class, isn't right?
Last edited on
From what I've read, overloading is a form of polymorphism, and in some texts, they are equivalent.
Please read the links I provided.

In the strict, C++, technical sense of the term, it means late-binding, or run-time link resolution. It has nothing to do with the ability to overload, only when the overload is resolved.
Ok, lets clean this mess up.

In a simple way, polymorphism is a callback inside a class, isn't right?


I was wrong. That's one of the implementation of polymorphism.
From what I've read, overloading is a form of polymorphism, and in some texts, they are equivalent.

If we depend on the meaning of poly-morph, then it could be.

But according to Douas' arguments, samples in wikipedia and C++.com/tutorial above...

http://en.wikipedia.org/wiki/Template_%28programming%29
http://www.cplusplus.com/doc/tutorial/polymorphism.html

We can conclude that polymorphism is (only) overriding abstract/virtual method from the base class. And in many case, the overrided method may interact to the base class behaviour.

BUT, there is something wrong in Wikipedia that might make us confusing...
Please take a look at: http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming#Overriding_and_Overloading

That's not a consistency one.
It is perfectly consistent.

Polymorphism (in the OOP sense) is when the method called is determined when the program is running. Everything else --overloads, operators, templates, etc-- are determined before the program ever runs.

To make it clear, let's play compiler for a moment.

The includes we'll need:
1
2
#include <iostream>
using namespace std;

Suppose we have a template class that overloads a method called "add" which adds two points together.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct point_t
  {
  int x, y;
  point_t( int x = 0, int y = 0 ): x( x ), y( y ) { }

  // first overload
  point_t add( const point_t& pt )
    {
    return point_t( x +pt.x, y +pt.y );
    }

  // second overload
  point_t add( int x, int y )
    {
    return point_t( this->x +x, this->y +y );
    }
  };

For your convenience at home, we'll also add an ostream insertion operator. We will totally ignore it for the purposes of this discussion. (You can think about it later.)
1
2
3
4
5
ostream& operator << ( ostream& outs, const point_t& pt )
  {
  outs << '(' << pt.x << ',' << pt.y << ')';
  return outs;
  }

So far, so good. Using the class is a breeze.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main()
  {
  point_t a( 10, 20 );
  point_t b(  5, -7 );
  point_t r;

  // first overload
  r = a.add( b );
  cout << a << " + " << b << " = " << r << endl;

  // second overload
  r = r.add( r.x *10 -r.x, r.y *10 -r.y );
  cout << "scaled by 10 = " << r << endl;

  return 0;
  }


Now, the question is: "is this polymorphic?"

To answer it, we'll pretend we are the compiler.

Initializations
First, we read everything and remember what stuff looks like. When we finally get to int main() we begin outputting executable instructions. We initialize the program and all the stuff outside the scope of our discussion.

Ok, now we get to line 3. We allocate room for a point_t, set x and y to 10 and 20, and remember its name is "a".
Likewise for line 4.
Line 5 is interesting. It is not overloaded, but it has default arguments. We are a smart compiler, so we set x and y both to zero.

First Overload
Now for the interesting stuff: line 8.
The user wants to use r's add() method. But there are two different versions of it defined.

So what we do is look to see if we can find a version of add() that takes the given type of argument: another point_t. Fortunately there is one (up on line 7 of the class specification), so that's the one we will use.

We compile line 8 using the first version of add().

Second Overload
Continuing on our way, we eventually get to line 12 and discover another call to add(). This time, however, we notice that the function is called with two int arguments. And again, we remember that line 13 above defines a version of add() that takes exactly that.

So we use the second version of add() to compile line 12.

Etc.

Reflections
In both cases, we were able to determine the exactly which function to call based on its "signature", or the types of its parameters. As a result we were able to compile the program exactly and it will run using the correct version of each function.

Since everything was done at compile-time, (and the function called cannot change at runtime), the answer to our question is "No, it is not polymorphic."


OK, so let's see some polymorphism in use...

(to be continued...)
Complicated reply Duoas.

Polymorphism. It's an OO rule that says if you have a child-class, you can treat it as if it were it's parent type.

e.g. You can treat Ant as if it were an Insect, you can treat Station Wagon, Coup as if they were "Cars".

1
2
3
4
5
Child *myChild = new Child();
Parent *myParent = (Parent*)myChild;

myParent->callFunc(); 
myChild->callFunc();


A common use for it is if you wanted to store a bunch of objects in a single vector (say Cars) then you could use vector<Car*> carList and then simply
1
2
carList.push_back(new SUV()); 
carList.push_back(new StationWagon()); // etc 


This assumes SUV and StationWagon are child classes to Car.

Polymorphism is most often utilized through the use of function 'over-riding' (not overloading). This your usual virtual and pure-virtual methods that will have an over-ride in the child.

That's the simplest explanation of Polymorphism.
Last edited on
Polymorphism is most often utilized through the use of function 'over-riding' (not overloading). This your usual virtual and pure-virtual methods that will have an over-ride in the child.

That's the simplest explanation of Polymorphism.

That's the simple one Zaita, thanks!

Because in C++ we can do high-level (abstract) featured things than low-level, we need a simple explanation of them.

Thanks too Douas!
Whoopsy. My bad.
Must have misread. XD
No worries :)
Wait a minute!

Douas, are You trying to explain that operator overloading is polymorphism...??
Last edited on
Nope, he was saying that overloading is "not polymorphic". :)
Pages: 12