Basic Polymorphism

Written by:dimport
Published by:CodeX
Published on:2003-06-21 07:19:46
Topic:C++

The first time i heard the term [i]polymorphism[/i] in the context of programming, i was pretty scared, it sounds daunting, and the way some people describe it, it can be, hopefully i can show you how easy it is.

Polymorphism, means having many forms which describes the programming concept quite well, essentially polymorphism (in its simplest form) allows you to have as many functions as you like of the same name, as long as the inputs are different, it works like this:

 #include <iostream.h>
 int add_stuff(int a, int b)
{
return (a+b);
}
 int add_stuff(int a, int b, int c)
{
return (a+b+c);
}
 int main()
{
cout << add_stuff(2, 3) << endl;
cout << add_stuff(2, 3, 6) << endl;
return 0;
}


As you can see, same name, different inputs, the compiler knows which function to call depending on the inputs passed, everyone's happy. Moving on, well now create a class and overload the constructor, the idea behind the constructor is to define an object, ie,

 #include <iostream.h>
 class rectangle
{
public:
rectangle();
rectangle(int length, int width);
~rectangle()
{
}
int GetLength()
{
return (rectLength);
}
int GetWidth()
{
return (rectWidth);
}
private:
int rectLength;
int rectWidth;
};
 rectangle::rectangle()
{
rectLength = 0;
rectWidth = 0;
}
 rectangle::rectangle(int length, int width)
{
rectLength = length;
rectWidth = width;
}
 int main()
{
rectangle aRect;
cout << aRect.GetLength() << endl;
cout << aRect.GetWidth() << endl;
 int aRectWidth = 10, aRectLength= 12;
 rectangle anotherRect(aRectWidth, aRectLength);
cout << anotherRect.GetLength() << endl;
cout << anotherRect.GetWidth() << endl;
 return 0;
}


ok, its not functional in any way, but you can see the effect, the right constructor is called depending on inputs, short of going into virtual functions and the ilk, which ill probably do at a later date, this as far as you can go with polymorphism.

This article was originally written by Pigsbig78

This is an article from http://www.osix.net - view the original at: http://www.osix.net/modules/article/?id=247