0

Using a function that looks like:

IntegerSet &insert(int m);

I'm trying to create a function that supports cascading calls that insert values into an object's array.

My function:

IntegerSet &IntegerSet::insert(int m) {
    IntegerSet newObj;
    for (int i = 0; i < 256; i++) {
        newObj.set1[i] = set1[i]; //copy the array into the new object
    }
    newObj.set1[m] = true;
    return newObj;
}

The object being returned is empty, which I suspect has to do with the reference.

Attempting to change it by altering the & to look like

IntegerSet IntegerSet::&insert(int m)

makes it refuse to compile because it 'expects an identifier'.

Joseph Thomson
  • 9,888
  • 1
  • 34
  • 38
Ozymandias
  • 156
  • 2
  • 5
  • 18
  • 6
    You're returning a reference to a local variable. Perhaps you might expand your example to include the definition for IntegerSet and how you're actually using it. You should read this: https://stackoverflow.com/questions/4643713/c-returning-reference-to-local-variable – Retired Ninja May 07 '17 at 05:11

2 Answers2

3

This is probably what you intended in order to make fluent syntax work:

IntegerSet& IntegerSet::insert(int m)
{
    this->set1[m] = true;
    return *this;
}

For fluent syntax, you typically want a lot of member functions called on the same object, not proliferation of temporary objects.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
1

You should not return a reference to a local, as it will have been destroyed by the time the function returns. However, you probably want to modify the IntegerSet on which you call insert instead and return a reference to *this. This is much more efficient than making a copy each time.

IntegerSet &IntegerSet::insert(int m) {
    set1[m] = true;
    return *this;
}

This way you can chain function calls on an IntegerSet object like so:

iset.insert(1).insert(2).insert(3);
Joseph Thomson
  • 9,888
  • 1
  • 34
  • 38