Pass Class Member to Method Argument

83 views Asked by At

how can I access class member in the function argument

class Array
{
private:
    int size;
public:
    void fill(int start = 0, int end = **size**)
        {
            // Function Body
        }
};

I tried to use that

public:
    void fill(int start = 0, int end = NULL)
        {
            if (end == NULL)
               end = size;
            // Function Body
        }
1

There are 1 answers

0
Alex On

I see a couple of use cases for your function:

Array a;
int start = ...;
int end = ...;
//first case
a.fill(start, end);
//second case
a.fill(start);
//third case;
a.fill();

In that case, I would define three methods: One to do the actual job and the other two as the convenience methods:

class Array
{
private:
    int size;
public:
//main method
    void fill(int start, int end)
    {
        // Function Body
    }
//convenience methods
    void fill(int start)
    {
        fill(start, size);
    }
    void fill()
    {
        fill(0, size);
    }
};

This is not recommended practice for C++, because your class then gets bloated with convenience methods. Imagine if you had more optional parameters per method call, you would have to write one convenience method per optional parameter.

Better solution is to simply remove default values for parameters and use explicit values each time. In the long term your code will not be any bigger and you keep the clarity of this method.

class Array
{
private:
    int size;
public:
    int getSize()
        {
            return size;
        }
    void fill(int start, int end)
        {
            // Function Body
        }
};

When using your code, you would then just have to write a few extra parameters:

int main()
{
    Array a;
    a.fill(0, a.getSize());
    //with default values it would be
    //a.fill();
}

If you see the use of no parameters as a particularly often occurrence, then write a single convenience method for it, but I would still argue that the example above is as clean as it needs to be.