-1

so i was trying to override the function max and i ran into lots of errors

> call of overloaded 'max(int&, int&)' is ambiguous

> /usr/include/c++/7/bits/stl_algobase.h:219:5: note: candidate: constexpr const _Tp& std::max(const _Tp&, const _Tp&) [with _Tp = int]
     max(const _Tp& __a, const _Tp& __b)
> 
> In file included from /usr/include/c++/7/bits/char_traits.h:39:0,
                 from /usr/include/c++/7/ios:40,
                 from /usr/include/c++/7/ostream:38,
                 from /usr/include/c++/7/iostream:39,
                 from prog.cpp:1:

my code :

#include<iostream>

using namespace std;

template <typename T>

T max(T a, T b)
{
    return a > b?a:b;
}

int main()
{
    cout<< max(5,4);

    return 0;
}

there a way to override builtin function or predefined functions?

even if i declare

int a(5),b(4);
cout<<max(a,b);

its giving me errors

  • 8
    Get rid of `using namespace std;` and your problems will go away. See also [Why is `using namespace std;` considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – alter_igel Mar 19 '20 at 03:28

1 Answers1

5

max is not a built-in function, it is part of the standard library. You are not trying to override/replace it, you are simply adding another function overload that will be considered during overload resolution and will make the call ambiguous, because both your overload and the standard library one's, which you imported with using namespace std;, will match.

Your problem is that you are using using namespace std;, which imports all the names from the standard library namespace std:: into the global namespace.

This is considered bad practice for the exact reason that it will cause issue such as yours.

Remove using namespace std; and instead either always prefix names from the standard library namespace with std::, such as std::cout, or import only a selected list of names, e.g.:

using std::cout;

However, there is no reason to define max yourself. std::max from #include<algorithm> already does exactly what you want max to do (only that it takes care of some edge cases that you are not considering).

Just use std::max (or max after using std::max;) and don't define your own implementation.

walnut
  • 21,629
  • 4
  • 23
  • 59
  • yeah i know about std::max but my second Question is how can i override such functions? like i want to override std::max how can i do it? – UnbeatableMaster Mar 19 '20 at 09:15
  • @UnbeatableMaster You can't "override" functions in that sense. Why do you think that you need to do that? – walnut Mar 19 '20 at 09:34