C ++, what default value can I give for an object?

I am new to C ++ programming, so please don't be too harsh :). The minimum description of my problem is illustrated by the following example. Let's say I have this function declaration in the header file:

int f(int x=0, MyClass a); // gives compiler error 

The compiler complains that parameters following a parameter with a default value must also have default values.

But what is the default value for the second parameter?

The idea is that a function could be called with less than two arguments if the rest is not specific, so all of 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

+4
source share
5 answers

You might also want to consider providing overloads rather than default arguments, but for your specific question, since the MyClass type has a default constructor, and if that makes sense in your design, you can default:

 int f(int x=0, MyClass a = MyClass() ); // Second argument default // is a default constructed object 

You can get more flexibility in custom code by manually adding overloads if you want:

 int f( MyClass a ) { // allow the user to provide only the second argument f( 0, a ); } 

You should also consider using links in the interface (take MyClass from the const link)

+4
source

I think you can do one 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 
+1
source

The best you can do is

 int f(MyClass a, int x=0); 

In this case, you can call the function with one parameter (MyClass) and the second default parameter or with two explicit parameters (MyClass, int).

0
source
 int f(int x=0, MyClass a = MyClass()); 
0
source

You can do

 int f(int x=0, MyClass a = MyClass()); 

and add constructor options if necessary.

0
source

Source: https://habr.com/ru/post/1403918/


All Articles