1

Chapter 7.6 of the book C++ Primer says the following:

A nonstatic data member may not be used as a default argument because its value is part of the object of which it is a member. Using a nonstatic data member as a default argument provides no object from which to obtain the member’s value and so is an error.

Member functions can access class members, so why is it a problem when a default argument is used by a member function?

L.S. Roth
  • 447
  • 2
  • 14
  • Because it isn't in scope at the call site. Which existing object's instance value would you like to use there? It doesn't make sense. – user207421 Oct 20 '21 at 09:36
  • @L.SRoth: I would just says it is a language choice. – Jarod42 Oct 20 '21 at 09:38
  • @user207421: *"Which existing object's instance"* the current one (`this`, so the instance which call the non-static method). It might make sense, it is not because C++ choose to not allow that (I think for simplicity), that it doesn't make sense. – Jarod42 Oct 20 '21 at 09:48

1 Answers1

1

The short answer is: There is no a priori reason why it wouldn't be possible, but in C++ there is no mechanism to do it (at least not directly).

Default arguments are substituted at the call site. For example

void foo(int x = 42);

Then

foo();

is actually

foo(42);

With non-static members this doesn't work:

struct bar {
    int y;
    void moo(int x = y);
};

bar b;
b.moo(); // -> b.moo(y) ?!?

The default argument is replaced at the call site and this is not necessarily in the scope of the class. Outside of the scope of the class you need an instance to access a member.

Surely there could be rules to make it work, but instead C++ just says you cannot do it. However, you don't need it because there is a straightforward workaround:

struct bar {
    int y;      
    void moo(int x);
    void moo() { moo(y); }
};
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185