What is the reason for not allowing in C++ a default value for a variable to be a non-static method or member of a class?

StackOverflow https://stackoverflow.com/questions/1848136

Question

I wanted to know why the default value for a variable for a method of a class, cannot be a non-static method or member of the same class.

Is there a reason for that ? Could not the compiler provide to the method the position in the class of the non-static default value ?

I tried to google quickly for an answer but I could not come up with a good answer.

EDIT: here is an example.

This is legal:

 class ClassTemp
{
  static int s_member;

  int MagicOperation(int defaultValue = s_member)
  {
    return defaultValue;
  }
};

But this is not:

class ClassTemp
{
  int m_member;

  int MagicOperation(int defaultValue = m_member)
  {
    return defaultValue;
  }
};
Was it helpful?

Solution

Default arguments are evaluated in the context of the caller (which is why they are usually called "arguments", not "parameters"), not in the context of the class method. This means that in order to evaluate these non-static arguments the compiler would need to know the specific class instance from which to take these default values.

Of course, it is possible in theory to allow using non-static members as default parameters and make compilers use the class instance that is specified in the member call. But that does not sound like "C++ way" of doing things to me. Also, it might lead to rather convoluted and inelegant specification in some more complicated cases, for example, when the method is virtual.

OTHER TIPS

The non static members are bound to a object and require 'this' pointer to access it . Since this pointer is not available for the default vaules it is not allowed

Off the top of my head, allowing default parameters from the class instance you're calling into, would require "derefing" the member value before making the call, due to function arguments getting pushed on the stack before the this pointer.

Secondly, there would be a small overhead in every call to that method utilizing the default value to the effect of:

push provided arguments...
push (this->member)
push this

These are pretty vague counter arguments, I see no reason why it can't be done either.

If I understand your question, it's because the compiler does know if the non-static variable that you are initializing this method var exists - thus the requirement that it be static so it's guaranteed to exist when the method var is initialized. It's not a matter of looking it up.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top