Search code examples
parametersdmember-functionsmember-variablesdefault-arguments

Is there a way to have dynamic default arguments?


I'm trying to make a class where the user can modify member variables to change the default arguments of its member functions.

class Class
{
    public int Member;

    public void Method(int Argument = Member)
    {
        // This compiles fine, until I try to actually use
        // the method elsewhere in code!

        // "Error: need 'this' to access member Member"
    }
}

My workaround so far has been to use magic numbers, which obviously isn't ideal.

public void Method(int Argument = 123)
{
    int RealArgument;

    if (Argument == 123) RealArgument = Member;
    else RealArgument = Argument;
}

Is there a better way, or am I stuck with this "hack" solution?


Solution

  • Yep, forget about the default argument.

    class Class
    {
        public int Member;
    
        public void Method(int Argument)
        {
            ...
        }
    
        public void Method()
        {
            Method(Member);
        }
    }
    

    No need for trickery here.