Function polymorphism/overloading based on parameter data type – CSKC
Sign In

Search

Code Learning #CPP#2263    siteicon   siteicon  

Function polymorphism/overloading based on parameter data type

Writing polymorphic function based on difference on parameters data type.

Learning Objectives

  • Understanding function overloading or polymorphism for same number of parameters but with different data types.

Source Code

TC++ #2263

 

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

  Related ( ? ) :

Code Understanding

void add(int);
void add(char);
These are two function prototype declaration with same name but with different type if input parameter.

char c=’#’; //This is input for char type parameter of function
int n=10; //This is input for int type parameter of function

add(c); 
This will call the version of add function where the char data type is the input.

add(n);
This will call the version of add function where the int data type is the input.

void add(char a){for(int i=0;i<10;++i) cout<<a;cout<<endl;}
This function takes char data type as input and prints the given character for 10 times.

void add(int n){int sum=0;for(int i=1;i<=n;++i) sum+=i;cout<<sum<<endl; }
This is function with same name (Polymorphic) but will do an entirely different job of taking an integer input and then make a sum of values from 1 to given input integer.

Notes

  • Polymorphism may be based on parameter data type also, even when the number of parameters are same.
  • Both number of parameter variables and type of data may be different at the same time.
  • Two polymorphic functions may do entirely different calculations but as a good programmer it is always recommended that the name of the function must be justified while writing the code inside a function.

Common Errors

  • Some time student try to write polymorphic functions with same count and same data type with different return types. This does not work in c++. For example –
    int repeat(char);
    void repeat(char); 
    Above two declarations will give error as only return data type is different. This makes calling a function ambiguous.


Suggested Filename(s): fn-poly-type.cpp



Share

Created: 5-Jan-2018 23:30 | Updated: 15-Sep-2018 14:10|