user1069609
user1069609

Reputation: 871

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

Upvotes: 6

Views: 11227

Answers (5)

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)

Upvotes: 5

cli_hlt
cli_hlt

Reputation: 7164

You can do a

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

and add constructor parameters as required.

Upvotes: 0

Kevin
Kevin

Reputation: 25269

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

Upvotes: 1

Robᵩ
Robᵩ

Reputation: 168626

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

Upvotes: 0

iehrlich
iehrlich

Reputation: 3592

The best you can do is

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

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

Upvotes: 0

Related Questions