Thread: A little on Function Overloading

  1. #1
    Registered User
    Join Date
    Mar 2002

    Question A little on Function Overloading

    K I just finished my bit of reading on function overloading and while I have the basic idea I got a question please. Let's say I have a function Multiply() which I overload by using different data types and return types, but same number of parameters
    int Multiply(int x , int y);
    double Multiply(double x , double y);

    and in main() I have an option which ask the user to enter to numbers to multiply is it that C++ automatically knows which overloaded function to use?

    cout << "Enter two numbers:";
    cin >> x >> y; //x or y being a double or a integer
    Multiply(x , y);

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Northern Virginia/Washington DC Metropolitan Area
    If the variables x and y are both integers, then the integer version of your function should be called, if they are doubles, then the doubles version should be called. So, it depends on what the variable type is. You could declare them as integers and the user could enter 5.2 and 6.4 but that doesn't mean that the double version would be called. The values would be converted into their integer counterparts and then the integer version of multiply would be called. I think that's how it works.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Visalia, CA, USA
    You can also overload operators. And you shouldn't depend on your compiler being a genious. You should explicitly tell it which function to use. By that I mean don't have lines of code that look like this:

    my_class.Multiply(4.0032, 6);

    Compilers always go with the larger data type in these situations but I wouldn't guarantee that the compiler won't assume that you are using the int version of Multiply. So make sure any line of code that looks like my example looks more like this:

    my_class.Multiply(4.0032, 6.0);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Post your games here...
    By Hammer in forum Game Programming
    Replies: 132
    Last Post: 02-28-2013, 09:29 AM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. Replies: 4
    Last Post: 11-23-2003, 07:15 AM