Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overload vs default parameters in c++ standard

I was reading another question, and it got me thinking. Often the standard specifies functions which have default parameters in their descriptions. Does the standard allow writing these as overloads instead?

For example, the standard says that std::basic_string::copy has the following declaration:

size_type copy(Ch* p, size_type n, size_type pos = 0) const;

Could a conforming implementation of the standard library implement this instead as two functions like this?

size_type copy(Ch* p, size_type n, size_type pos) const;
size_type copy(Ch* p, size_type n) const;

In this example, the second version could skip the if(pos > size()) { throw out_of_range(); } test that is necessary in the first one. A micro-optimization, but still you see the point of the example.

like image 796
Evan Teran Avatar asked Feb 17 '11 16:02

Evan Teran


People also ask

Does C allow default parameters?

There are no default parameters in C. One way you can get by this is to pass in NULL pointers and then set the values to the default if NULL is passed.

Can we overload function with default arguments?

No you cannot overload functions on basis of value of the argument being passed, So overloading on the basis of value of default argument is not allowed either.

What is function overloading compare default arguments with function overloading?

Default arguments are a convenience, as function overloading is a convenience. Both features allow you to use a single function name in different situations. The difference is that with default arguments the compiler is substituting arguments when you don't want to put them in yourself.

Does C have overload?

No, C does not support overloading, but it does support Variadic functions. printf is an example of Variadic functions.


1 Answers

Could a conforming implementation of the standard library implement this instead as two functions like this?

Yes. The C++ Standard (C++03 17.4.4.4/2-3) says:

An implementation can declare additional non-virtual member function signatures within a [Standard Library] class:

-- by adding arguments with default values to a member function signature; the same latitude does not extend to the implementation of virtual or global or non-member functions, however.

-- by replacing a member function signature with default values by two or more member function signatures with equivalent behavior;

-- by adding a member function signature for a member function name.

A call to a member function signature described in the C + + Standard library behaves the same as if the implementation declares no additional member function signatures

like image 74
James McNellis Avatar answered Oct 03 '22 20:10

James McNellis