c++function

C++. Can we have same named function, but in different file?


Lets say that i have three .cpp files and 2 header files.

1st file:

it main.cpp, it calls all function and stuff. the 2 header files are included.


2nd file:

Contains two functions:

int print(int num2, int num1)

and

int update(int num1)

3rd file:

Contains three functions:

int calculate(int num2, int num3, int num4)

and

int update(int num2, char random)

and

int divied(int all)

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

As you can tell that 2nd and third file have one same named function "int update" but in one it has 1 parameter and in the other it has two.

Will I be able to call the one i want? will i get compile errors? I can't test it right now cause i am using the libraries computer.


Solution

  • Technically, yes, you will. Functions with different signature form an overload set, and on call the proper one will be selected by matching the number and type of actual parameters passed.

    OTOH it is an awful practice to have such name sitting around in the global namespace. It's just accident waiting to happen -- someone will call the unintended function by a typo.

    Real overload sets are not formed randomly but by design: that is the a function having the same semantics, just using a different kind of ammo. They are meant to work in coalition, and work best when answer to "which one is called" is "I don't care". As whichever the compiler selects will do the proper job.