Lets say we have the following files :-
add.h
int add(int x, int y); // function declaration includes return type, name, parameters, and semicolon. No function body!
add.cpp
#include "add.h" // Insert contents of add.h at this point. Note use of double quotes here.
int add(int x, int y)
{
return x + y;
}
main.cpp
#include "add.h" // Insert contents of add.h at this point. Note use of double quotes here.
#include <iostream>
int main()
{
std::cout << "The sum of 3 and 4 is " << add(3, 4) << '\n';
return 0;
}
What if add.cpp only contained :-
add.cpp
int add(int x, int y)
{
return x + y;
}
So what if we changed something in add.cpp but not in add.h ? For example
add.cpp
double add(int x, int y)
{
return x + y;
}
main.cpp
#include "add.h" // Insert contents of add.h at this point. Note use of double quotes here.
#include <iostream>
int main()
{
std::cout << "The sum of 3 and 4 is " << add(3, 4) << '\n';
return 0;
}
add.h
int add(int x, int y); // function declaration includes return type, name, parameters, and semicolon. No function body!
Then look preprocessor will include add.h into main.cpp which will look like this :-
main.cpp
int add(int x, int y);
#include <iostream>
int main()
{
std::cout << "The sum of 3 and 4 is " << add(3, 4) << '\n';
return 0;
}
main.cpp , add.cpp will ALL OF THEM INDIVIDUALLY compile sucessfully but LINKER WILL GIVE ERROR BECAUSE IT WILL NOT BE ABLE TO FIND IMPLEMENTATION OF int add(int x, int y); WHICH WAS IS NEEDED IN FUNCTION CALL IN MAIN.CPP. BECAUSE WE HAVE THE IMPLEMENTATION OF double add(int x, int y); IN add.cpp.
INSTEAD IF #include "add.h" WAS ALREADY PRESENT IN ADD.CPP THEN
add.cpp
#include "add.h" // Insert contents of add.h at this point. Note use of double quotes here.
double add(int x, int y)
{
return x + y;
}
PREPROCESSOR WOULD CONVERT IT TO
add.cpp
int add(int x, int y)
double add(int x, int y)
{
return x + y;
}
WHICH IS COMPILER ERROR IT WILL BE AN ADD.CPP COMPILE TIME ERROR. THIS IS ALSO NOT A VALID FUNCTION OVERLOADING ALSO BECAUSE IN FUNCTION OVERLOADING NAME OF THE FUNCTION SHOULD REMAIN SAME AND NUMBER OF PARAMETERS ARE DIFFERENT BUT RETURN TYPE CANNOT BE USED AS A BASIS FOR FUNCTION OVERLOAD.