Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing variable in C++ function header

I've come across some C++ code that looks like this (simplified for this post):

(Here's the function prototype located in someCode.hpp)

void someFunction(const double & a, double & b, const double c = 0, const double * d = 0);

(Here's the first line of the function body located in someCode.cpp that #include's someCode.hpp)

void someFunction(const double & a, double & b, const double c, const double * d);

Can I legally call someFunction using:

someFunction(*ptr1, *ptr2);

and/or

someFunction(*ptr1, *ptr2, val1, &val2);

where the variables ptr1, ptr2, val, and val2 have been defined appropriately and val1 and val2 do not equal zero? Why or why not?

And if it is legal, is this syntax preferred vs overloading a function to account for the optional parameters?

like image 656
Evan Avatar asked May 13 '11 09:05

Evan


1 Answers

Yes, this is legal, this is called default arguments. I would say it's preferred to overloading due to involving less code, yes.

Regarding your comment about const, that doesn't apply to the default value itself, it applies to the argument. If you have an argument of type const char* fruit = "apple", that doesn't mean it has to be called with a character pointer whose value is the same as the address of the "apple" string literal (which is good, since that would be hard to guarantee). It just means that it has to be called with a pointer to constant characters, and tells you that the function being called doesn't need to write to that memory, it is only read from.

like image 123
unwind Avatar answered Oct 08 '22 06:10

unwind