overload

Im having difficulties understanding overload operationd especially with objects
& pointers. So i need to know which book did you guys use to understand this concepts?
Function (and operator) overloading is nothing more than writing two or more functions
with the exact same name, but each of which take different parameters. The idea is
that the compiler can determine which function you are trying to call by looking at
the number and types of parameters you are passing.

Example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>

void foo( int x ) {
   std::cout << "Version 1" << std::endl;
}

void foo( std::string x ) {
   std::cout << "Version 2" << std::endl;
}


void foo( int x, int y ) {
   std::cout << "Version 3" << std::endl;
}

int main() {
    foo( 4 );   // Calls "Version 1" since 4 is an int.
    foo( std::string( "Hello World" ) );  // Calls "Version 2" since parameter is a string
    foo( 4, 5 );  // Calls "Version 3"
}

Topic archived. No new replies allowed.