On Sep 23, 12:17 am, "Bo Persson" <b...@gmb.dk> wrote:
Divick wrote:
On Sep 21, 11:22 pm, "Bo Persson" <b...@gmb.dk> wrote:
Divick wrote:
Hi,
I have the following code (see below). My compiler g++ 3.4.6
doesn't compile it. I wonder why shouldn't this be allowed? I
understand that const int a, would be different for different
objects, unlike static const. And functions are common for all
objects. But from the compiler's perspective, shouldn't it be
simple to handle as for every invocation of a function with
default argument, if the value is not supplied then the
compiler can simply initialize the function with the value on
which the function has been called?
class x
{
private :
const int a;
public :
X() : a(1)
{}
void foo(int arg = a)
{
cout << arg << endl;
}
};
It is not actually a bad idea, however it is expressly
forbidden by the standard. Default arguments cannot use
non-static members, or the keyword 'this'.
If you make a static it will work, but of course share its value
between all x objects.
As a workaround, you can add an overload that gets the correct
value:
void foo()
{
foo(a);
}
Bo Persson
I think I could guess that it is not allowed by the standard,
but my question was originally about why it is not allowed.
Unless there is a good reason for disallowing it in the
standard, the standard could have allowed non static default
argument as well.
The standard usually doesn't give any reason for the rules, it
just states what they are.
In this case, I agree that it would be feasible for the caller to
supply not only the 'this' pointer, but also 'this->a' as a
parameter value (with the exception that as a is private, it is a
bit questionable if it should :-).
I can only imagine that as the 'this' pointer is formally
provided by magic inside the member function, perhaps we cannot
require that the caller knows what it is, so in theory there are
cases where it cannot provide this->a.
Bo Persson
Could you post some example /cases where it doesn't know what
this->a is? In earlier post by Bart, he points to the fact that
variable a is inaccessible in the scope of main because it is
private. But here we are not talking about visibility at the
language level but visibility at the compiler level. Compiler does
have knowledge / visibility of this->a, while in the context of
language / scope, surely the variable is not accessible. I would
assume that default arguments are something that are dealt by the
compiler and during the runtime.