I have the following code in C++ . Everytime I run it ,it has a different output. Why does this happen ? Is it somehow related to memory leak ?
#include <iostream>
using namespace std;
template <class T, class U>
T f(T x, U y)
{
return x+y;
}
int f(int x, int y)
{
return x-y;
}
int main()
{
int *a=new int(4), b(16);
cout<<*f(a,b);
return 0;
}
You are passing a pointer and a normal
int
tof
, becauseworks like
Thus, in
f
, you haveT == int*
andU == int
, then you add theint
to the pointer and return the resulting pointer. As it does not point to memory you own and initialized, dereferencing it is UB and may yield garbage or crash or do whatever it likes.As I already said in the comments, you should not try to learn C++ by trial and error, that really will not work, believe me. Learn it systematically from a good book instead. You will see that there is no need to use pointers for this in the first place.