I'm new in C++ programming, so please don't be too harsh now :) . A minimal description of my problem is illustrated by the following example. Say I have this function declaration in a header file:
int f(int x=0, MyClass a); // gives compiler error
The compiler complains because parameters following a parameter with default value should have default values too.
But what default value can I give the second parameter?
The idea is that the function could be called with with less than two args if the rest isn't relevant for a particular case, so all the following should go:
MyClass myObj; // create myObj as an instance of the class MyClass
int result=f(3,myObj); // explicit values for both args
int result=f(3); // explicit for first, default for second arg
int result=f(); // defaults for both
You might want to also consider providing overloads rather than default arguments, but for your particular question, because the MyClass
type has a default constructor, and if it makes sense in your design, you could default to:
int f(int x=0, MyClass a = MyClass() ); // Second argument default
// is a default constructed object
You can gain greater flexibility in user code by manually adding overloads if you wish:
int f( MyClass a ) { // allow the user to provide only the second argument
f( 0, a );
}
Also you should consider using references in the interface (take MyClass
by const reference)
I think you can do either of the following:
int f(MyClass a, int x=0); // reverse the order of the parameters
int f(int a=0, MyClass a = MyClass()) // default constructor
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