How do set a default parameter....

J

JustSomeGuy

Hi I have a function that takes a refrence to a std::list<myType> &
for ex:
myMethod(int a=0, int b=0, std::list<myType> & lst=NULL)

Now most of the time the lst is not passed and so I would like to have
it given a null parameter...
How do I do this?
 
J

Jakob Bieling

JustSomeGuy said:
Hi I have a function that takes a refrence to a std::list<myType> &
for ex:
myMethod(int a=0, int b=0, std::list<myType> & lst=NULL)

Now most of the time the lst is not passed and so I would like to have
it given a null parameter...
How do I do this?

Use a pointer instead of a reference.

hth
 
G

Gavin Deane

JustSomeGuy said:
Hi I have a function that takes a refrence to a std::list<myType> &
for ex:
myMethod(int a=0, int b=0, std::list<myType> & lst=NULL)

Now most of the time the lst is not passed and so I would like to have
it given a null parameter...
How do I do this?

It's not possible to have a null reference. If it is meaningful to
sometimes pass a list to your function and sometimes not, then use a
pointer parameter.

Gavin Deane
 
A

Alf P. Steinbach

* JustSomeGuy:
Hi I have a function that takes a refrence to a std::list<myType> &
for ex:
myMethod(int a=0, int b=0, std::list<myType> & lst=NULL)

Now most of the time the lst is not passed and so I would like to have
it given a null parameter...
How do I do this?

Almost as you did, except NULL is not an object of the right type.

However, it's generally bad design to have an optional out (or in/out)
parameter represented as a reference argument.

Instead, how about representing that as the function result?

Let's say 'myMethod' is really 'fixThings', and the troublesome argument
is a list of things fixed.

Then, how about

struct IRecorder
{
virtual void add( MyType const& ) = 0;
};

void fixThings( IRecorder& recorder, int a = 0, int b = 0 )
{
...
};

void fixThings( int a = 0, int b = 0 )
{
struct DummyRecorder: IRecorder { void add( MyType const& ) {} };
DummyRecorder r;
fixThings( r, a, b );
}

std::list<MyType> fixThingsWithRecording( int a = 0, int b = 0 )
{
struct Recorder: IRecorder
{
std::list<MyType> records;
void add( MyType const& o ){ records.push_back( o ); }
};
Recorder r;
fixThings( r, a, b );
return r.records;
}

Or something -- it depends very much on the actual problem.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,792
Messages
2,569,639
Members
45,353
Latest member
RogerDoger

Latest Threads

Top