Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 607
user1069609 Avatar asked Mar 28 '12 14:03

user1069609


2 Answers

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)

like image 54
David Rodríguez - dribeas Avatar answered Oct 27 '22 00:10

David Rodríguez - dribeas


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
like image 44
Kevin Avatar answered Oct 27 '22 00:10

Kevin