Saturday, May 22, 2010

I have a question about function overloading in OOP using C++?

I have two functions sum() with the following prototypes





int sum(int,int);


float sum(float,float);





I am calling these two functions from main(), by sending two int values and two float values to their respective sum() functions. And i will return sum of two integers and two float values from these two functions, which i will display on the screen.





But the compiler is taking both the functions as a single function. And i am getting ambiguity error. Why is this so?





The concept of function overloading is, a fucntion name is same but the number of arguments and/or return type should be different.





But if i change the second function's prototype to any of the following type it works well.


float sum(double,double);


int sum(double,double);





Will any one explain me the concept or internally what is happening? Also if i give the prototype double sum(float,float);





it is not working and giving the same stupid answer(ambiguity).





I am using C99 compiler and dev CPP compiler

I have a question about function overloading in OOP using C++?
The problem is that C doesn't allow overloading. It's a C++ thing. Try using a C++ compiler instead, or rename your functions to indicate the type of perameters they take ie. sumi(int, int) sumf(float, float)
Reply:the "signature"of a function consists of it's name and it's formal parameter list. functions can be overloaded if the the name is the same but the formal parameter list in each is different. the signature does not include the return type.





EX :


int funcABC(int x, int y)


float funcABC(float x, float y)


these examples should build without error





double funcABC(double x, double y)


void funcABC(double x, double y)


these should not build because the formal parameter list is the same in each function so the complier will generate an error. which function do i really want, since the names are the same and the paramter list is the same ?? the compiler is saying "come on fella you have me confused". note that the return types are different, but as i said earlier the return types are not included in the signature.





so, looking at your examples it would appear that you have them backwards. the


float sum(double,double);


int sum(double,double);


should cause the compiler to barf because the function signatures are the same and that's a nono

bridal flowers

No comments:

Post a Comment