PDA

View Full Version : What is wrong with this code?



Jeffb
17th February 2011, 05:38
I downloaded some code and I get this error. It looks ok to me.

Here's the declaration in the .h file.


void SetBorder( bool useBorder, QBrush& borderBrush = QBrush() );

Here's the .cpp code:

void JBWidget::SetBorder( bool useBorder, QBrush& borderBrush )
{
.....
}

Here's the error:
error: default argument for parameter of type 'QBrush&' has type 'QBrush'

Why can't it do this?

Cheers
Jeff

tbscope
17th February 2011, 06:05
Did you include QBrush?

ChrisW67
17th February 2011, 07:03
The default value type must be implicitly convertible to the parameter type. Default values are constants, so you cannot take a non-const reference to one.

What are you expecting to achieve? By passing the borderBrush parameter by reference you are saying that SetBorder() wants to modify the brush. On the other hand you are saying this parameter is usually just a default value, i.e. the caller usually doesn't provide a value or, by extension, want your modification.

You could declare it as:


void SetBorder( bool useBorder, const QBrush& borderBrush = QBrush() );

and your compiler will not throw the error. Your method will not be able to modify the brush though.

Jeffb
18th February 2011, 05:25
Thanks for the quick response.

I did include QBrush so I assume its the second reason.

Although given that I downloaded this code from gitorious as a working example, I'm a bit bewildered why it would have worked for the author and not for me or, alternatively, why they would put up a piece of code that doesn't compile.

Thanks for the help.

Cheers
Jeff

ChrisW67
18th February 2011, 07:22
A lesson I learned many, many years ago... A developer putting something into source control does not mean it compiles, runs, or works as required (or even as designed).

SixDegrees
18th February 2011, 07:34
Also, some compilers will incorrectly create an anonymous variable based on the assignment shown. This is wrong, but it allows such constructs to compile. So it may be that the original author is using a crappy compiler, and doesn't know any better than to avoid writing code like this.

Jeffb
18th February 2011, 07:35
Thanks Chris

I'll keep that in mind.

Jeff