I have a problem with the following code:
IntegerSet& IntegerSet::unionOfIntegerSets(IntegerSet a){
IntegerSet result;
for (int i = 0; i < 100; i++){
if ((array[i] == 1) || (a.getElement(i) == 1)){
result.setElement(i, 1);
}
}
return result;
}
The errors are:
-
reference to local variable ‘result’ returned [enabled by default]
-
call of overloaded ‘IntegerSet()’ is ambiguous
Can you tell me what I’m doing wrong? Thank you!
Header file:
#ifndef INTEGERSET_H_
#define INTEGERSET_H_
class IntegerSet{
private:
int* array;
public:
IntegerSet();
IntegerSet(int, int, int, int, int);
~IntegerSet();
int getElement(int);
void setElement(int, int);
IntegerSet& unionOfIntegerSets(IntegerSet);
IntegerSet insertionOfIntegerSets(IntegerSet);
void setPrint();
};
#endif
What is the workaround for this?
EDIT
IntegerSet IntegerSet::unionOfIntegerSets(IntegerSet a){
IntegerSet result;
for (int i = 0; i < 100; i++){
if ((array[i] == 1) || (a.getElement(i) == 1)){
result.setElement(i, 1);
}
}
return result;
}
The error is:
- call of overloaded ‘IntegerSet()’ is ambiguous
The first error is exactly as it says. You are returning a reference to a local variable.
resultis declared on the stack. It will die after the function ends, therefore whatever references to it will becoming invalid and dangling.As for the second error, we need to see the definition of the
IntegerSetclass to see where the ambiguity is.EDIT : You should also define a copy constructor for your class.
EDIT 2: Okay, I think I figured it out:
Does your the definition for the second constructor looks something like this?
I tried this and I got the ambiguous overload call that you got.
In this case, calling the constructor with no parameters can go to either constructor call – hence the ambiguity. So what you should do it get rid of the default value for the first parameter.