I want to give a default value to a function parameter, which is reference to a structure . What can I give as the default value ?
A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.
For variables of class types and other reference types, this default value is null . However, since structs are value types that cannot be null , the default value of a struct is the value produced by setting all value type fields to their default value and all reference type fields to null .
Default arguments are only allowed in the parameter lists of function declarations and lambda-expressions, (since C++11) and are not allowed in the declarations of pointers to functions, references to functions, or in typedef declarations.
In computer programming, a default argument is an argument to a function that a programmer is not required to specify. In most programming languages, functions may take one or more arguments. Usually, each argument must be specified in full (this is the case in the C programming language).
First solution:
If it is a reference to a struct, then you've to make it const
reference, and do this:
struct A
{
//etc
A(int, int);
};
void f(int a, const A & = A(10,20) ) //const is necessary
{
//etc
}
Its not that good for the obvious reasons: it makes the parameter const
(you may not want it), and your struct needs to have constructor (you may not have it).
Second solution:
So if you don't want to make it const
, or if you don't want to have a constructor in the struct, then you can do this:
struct Point
{
int x, y, z;
};
Point g_default_point = {10,20,30};
void g(int a, Point & p = g_default_point )
{
//etc
}
Still not good. Defining a global variable is not a great idea.
void g(int a, Point & p)
{
//your code
}
void g(int a) //this function would behave as if you opt for default value!
{
Point default_value = {10,20,30};
g(a, default_value);
}
Now it doesn't require you to make the parameter const
, neither does it force you to have constructor in your struct.
This works in C++0x:
#include <iostream>
struct structure { int x, y ; } ;
int f(int a, structure &s = structure{10,20}) {
return s.x + s.y ;
}
int main() {
std::cout << f (99) << std::endl ;
}
Note that s
does not have to be const
. See http://ideone.com/sikjf.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With