Reputation: 166
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'.
Upvotes: 0
Views: 1081
Reputation: 10433
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);
Upvotes: 1
Reputation: 283793
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.
Upvotes: 3