Detailed Print – CSKC
Sign In

Search

siteicon
Code Learning#CPP#4643 Back

Operator having many forms

Demonstration of a kind of polymorphism with + operator.

Learning Objectives

  • Understanding how operators can also show polymorphic behaviour.

Source Code

		 

Click to open popup

Run Output

12
polymorphism

Code Understanding

int a=5,b=7;  int c=a+b; cout<<c<<endl;
Here + (addition operator) is being used for adding two integers

string x=”poly”; string y=”morphism”; string z=x+y; cout<<z<<endl;
Here + (addition operator) is being used for concatenating two string, second one after the first string.

In both cases + acts as a binary operator, but operands are acted differently when their data types are different.

Notes

  • This code can not be demonstrated in Turbo C++ as you don’t have string datatype there
  • Many operators are already overloaded by default in C++ library, but programmers can also use there own code to make their own overloading action to overloaded operators.
  • Since operator overloading is a type of compile time overloading only, so purists consider this also a type of adhoc polymorphism. Read More..

Common Errors

  • The + operation doesn’t work for c-style (character array with null termination) strings. There one is required to use strcat() function.


Suggested Filename(s): plus-ol.cpp,plus-overloading.cpp