I am helping out my brother with some C++ revision work and.. well i am stumped.
He has to annotate the following code demonstrating where polymorphism is used.
class Addition
{
public:
void sum (int a, int b)
{
cout << a+b;
}
void sum (int a, int b, int c)
{
cout << a+b+c;
}
}; // end class
int main ()
{
system("CLS"); // clear the screen
Addition myObject; // declaring a new object
myObject.sum(10, 20); //
cout << endl;
myObject.sum(10, 20, 30); //
getch();
return 0; // terminating the main() function and returning a value of 0
}
can someone offer some pointers as i really don't know how to help
Polymorphism means "many forms" or "many shapes". In CS it basically means 1 thing has multiple behaviors. Typically we think of polymorphism as inheritance with virtual functions such that a call to a virtual function on a base class pointer (or reference) can have multiple results depending on what kind of derived class is being accessed. That's NOT what's happening here.
The polymorphism we see in this example is function overloading. The same function name has multiple behaviors (adding 2 values vs. adding 3 values) depending on how the function is called. I think most programmers here would avoid the use of the word "polymorphism" in this case and simply call it function overloading, but technically this could be considered polymorphic.
thanks doug4 thats a cracking answer, yea one reason why i reached out to this forum was that upon researching it, it did seem to flag more overloading info than polymorphism.
overloading is having 2 functions with the same name and different inputs. you have 1 version with 2, and another with 3. One of the most common overloads you will see, over and over, is the class constructor (may have a default one, a copy one, an initializing one or more in a class).
As Doug said, I don't really consider this to be polymorphism, but I suppose technically it is.
Incidentally, template instantiation is technically another form of polymorphism. It would be compile-time polymorphism (similar to function overloading) as opposed to run-time polymorphism (virtual function calls).
Not that this has anything to do with the question at hand, but since my professor stressed this to me <big number> years ago, I just thought I would just mention it here.