On 21 Set, 11:53, Divick <divick.kish...@gmail.com> 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;
> }
>
> };
>
> Thanks in advance,
> -DK
If I got it right, members functions aren't much different from normal
functions, that is, you should think of your "foo(int)" as something
like "foo(int, A* this)", because the function itself is not aware of
the object it is called upon and needs the "hidden 'this' argument" to
be aware of it.
Unfortunately you cannot even write something like "void foo(int arg =
this->a)", because the 'this' pointer is visible only inside of the
function's body.
If you need a workaround, one way could be to decide a range of values
that lead to use the const value, such as:
-------
class A {
const int i;
public:
A(int v = 0) : i(v) {}
int foo(int v = -1) {
if(v < 0) {
return i;
} else {
return v;
}
}
};
-------
For what is worth, hope that helps.
Have good time,
Francesco
--
Francesco S. Carta, hobbyist
http://fscode.altervista.org