8

The following code won't compile. Why?

class A
{
   int j;
   void f( int i = this->j );
}

Edit, for clarity. This is what I was trying to do, using less lines of code...

class A
{
   void f( int i ){};
   void f( );
   int j;
};

void A::f()
{
    f( j );
}
alexandreC
  • 481
  • 5
  • 13
  • 3
    Because the instance is not in scope inside the argument declaration...? – Kerrek SB Oct 10 '12 at 20:59
  • 2
    "...The expression can combine functions that are visible in the current scope, constant expressions, and global variables. The expression cannot contain local variables or non-static class-member variables..." – Adriano Repetti Oct 10 '12 at 21:02
  • @Jordan Kaye - I have edited, to answer your question... I was trying to use less lines of code... as described above. – alexandreC Oct 10 '12 at 21:07

2 Answers2

11

Default argument values are bound at compile time.

"this" is only defined at run time, so can't be used.

See here for a fuller explanation: Must default function parameters be constant in C++?

Community
  • 1
  • 1
Eric
  • 3,142
  • 17
  • 14
0

Others have already commented on the reason this doesn't work. From one of the comments:

"...The expression can combine functions that are visible in the current scope, constant expressions, and global variables. The expression cannot contain local variables or non-static class-member variables..."

You could use optional to eliminate the extra function although I'm not sure it's clearer:

void f( boost::optional<int> i = boost::none ) { if(!i) i = j; ... }

Mark B
  • 95,107
  • 10
  • 109
  • 188