PDA

View Full Version : C++ and default values for functions



guestgulkan
2nd January 2007, 18:00
When I learnt a bit about c++ and read about default values for function parameters,
I thought what a good idea - it was something I always wanted.
However, I find that they can be a great source of ambiguity when reading other peoples code.
Does anybody here use default values much or simply avoid them?

wysota
2nd January 2007, 18:12
What kind of ambiguity? I use them all the time and I don't encounter ambiguities... Qt uses default values almost everywhere and you don't hear people complaining about it... Could you elaborate on the problem?

guestgulkan
2nd January 2007, 18:38
For example - you are reading some code from someone else,
you see a funtion called with two parameters - is it a function
that only takes two parameters only , or is it a function
that takes more than 2 parameters, but in this case the uses have made use of the defaults?

Which would you assume?

jacek
2nd January 2007, 21:11
you see a funtion called with two parameters - is it a function
that only takes two parameters only , or is it a function
that takes more than 2 parameters
But why should I care if takes 2 or more parameters? If it matters, then most likely the code is poorly designed. Default values are not bad, one just might use them in a wrong way, but this doesn't mean you should avoid them.

wysota
2nd January 2007, 22:53
For example - you are reading some code from someone else,
you see a funtion called with two parameters - is it a function
that only takes two parameters only , or is it a function
that takes more than 2 parameters, but in this case the uses have made use of the defaults?

Default arguments should be used when the functionality they carry is optional. Well designed API should be intuitive, so it should make sense to you to call the function with two parameters. If you needed more functionality out of this function, you'd look at its docs and notice it has additional parameters which tweak the way the function works. Then you can use those parameters to alter the behaviour of the function. Treat a call with default arguments as a base functionality of the function and a call with all arguments used as an extended one.

As for your question - I don't care how many parameters a function takes. I only care what the function does and I don't have to look at its sources to find out. Well designed APIs are either very intuitive or very well documented (or both).