Question

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?

Was it helpful?

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.

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