svb@cs.purdue.EDU (Stephan Bechtolsheim) (05/21/91)
Look at the following source code please: ----------------------------------------------------------------- #include <stream.h> // Have three functions with almost identical signatures. int F (int); int F (int &); int F (const int &); int F (int a) { cout << "int F (int) called, argument = " << a << "\n"; return 0; } int F (int &a) { cout << "int F (int &) called, argument = " << a << "\n"; return 0; } int F (const int &a) { cout << "int F (const int &) called, argument = " << a << "\n"; return 0; } int main() { // **************************************** // And here is a function call. WHICH F?!?! // **************************************** int k = F(12); // which F?! exit (0); } -------------------------------------------------------- Question 1: which F should the compiler pick? With g++ it pickes the first one, but WHY?! Question 2: C++ would not allow you to do this though: int F (const int); int F (const int a) { cout << "int F (const int) called, argument = " << a << "\n"; return 0; } Then g++ (1.37....) complains. Anyone any insight? Thanks. Stephan v. Bechtolsheim Computer Sciences Department svb@cs.purdue.edu Computer Science Building (317) 494 7802 Purdue University FAX: (317) 494 0739 West Lafayette, IN 47907
steve@taumet.com (Stephen Clamage) (05/22/91)
svb@cs.purdue.EDU (Stephan Bechtolsheim) writes: >Look at the following source code please: >// Have three functions with almost identical signatures. >int F (int); >int F (int &); >int F (const int &); The first two declarations cannot be distinguished, and the compiler should complain about them. Evidently, your compiler does not complain, and picks one arbitrarily. If overloaded function signatures differ only in that of two corresponding parameters, one is type T and the other is T&, the declarations are inherently ambiguous and should be detected a compilation time. On the other hand, these two int F(int&); int F(const int&); are not ambiguous: int i; const int ci; F(i); // calls f(int&), since it is an exact match F(ci); // calls f(const int&), since it is an exact match -- Steve Clamage, TauMetric Corp, steve@taumet.com