Operator having many forms – CSKC
Sign In

Search

Code Learning #CPP#4643    siteicon   siteicon  

Operator having many forms

Demonstration of a kind of polymorphism with + operator.

Learning Objectives

  • Understanding how operators can also show polymorphic behaviour.

Source Code

TC++ #4643

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

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



Share

Created: 6-Sep-2018 19:35 | Updated: 6-Sep-2018 20:02|