default parameters: question

N

Neil Zanella

Hello,

It seems to me that default parameters can be anything including something
called with a constructor, but using the this pointer in as a default
parameter inside is not allowed it seems, as compiling the following
program illustrates. I wonder what the C++ standard has to say about
this. I am also interested in knowing why the designers of C++
decided to disallow this feature.

Best Regards,

Thanks,

Neil

class Foo {
public:
Foo(int x = 0): x(x) { }
private:
Foo *hello(Foo *foo = this); //invalid
int x;
};

Foo *Foo::hello(Foo *foo) {
return foo;
}

int main() {
Foo foo;
}
 
D

David Hilsee

Neil Zanella said:
Hello,

It seems to me that default parameters can be anything including something
called with a constructor, but using the this pointer in as a default
parameter inside is not allowed it seems, as compiling the following
program illustrates. I wonder what the C++ standard has to say about
this. I am also interested in knowing why the designers of C++
decided to disallow this feature.

Best Regards,

Thanks,

Neil

class Foo {
public:
Foo(int x = 0): x(x) { }
private:
Foo *hello(Foo *foo = this); //invalid
int x;
};

Foo *Foo::hello(Foo *foo) {
return foo;
}

int main() {
Foo foo;
}

The C++ standard, 8.6.3.8:

The keyword this shall not be used in a default argument of a member
function. [Example:
class A {
void f(A* p = this) { } // error
};
-end example]

D&E didn't provide any insight into why this is forbidden.
 

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

No members online now.

Forum statistics

Threads
474,172
Messages
2,570,934
Members
47,479
Latest member
JaysonK723

Latest Threads

Top