Hi All,

I have a question about the following C++ program:
How does the C++ program know which of the sqr functions to use in this program?

#include <iostream.h>
// This program illustrate the use of Function overloading
int sqr(int x);
float sqr(float x);
double sqr(double x);

int main(void)
{ // declare three variable of different types
int val1=4;
float val2=4.1;
double val3=4.123456;
// get the data from the user and call each version of function
cout << "Square of 4 is " << sqr(val1) << "\n";
cout << "Square of 4.1 is " << sqr(val2) << "\n";
cout << "Square of 4.123456 is" << sqr(val3) << "\n";
return(0);
}
// now declare the three function versions
int sqr(int x) {
return(x*x);
}

float sqr(float x) {
return(x*x);
}
double sqr(double x) {
return(x*x);
}

It matches the type you use when you call it to choose the correct one.

Btw, <iostream.h> is deprecated. Use <iostream> instead. ;)

It matches the type you use when you call it to choose the correct one.

That's the simple[and corect] answer.


If you want to know more see this or a user friendly version by Microsoft. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.