UrhoKarila
UrhoKarila

Reputation: 354

invalid initialization of non-const reference

Alright, I'm trying to figure out this error and have, so far, had absolutely no luck. I'm doing this for homework, which is why I'm not using included classes.

Here's the relevant code:

//Will return an array where each element is the sum of the respective sums in the added         arrays
Vec& Vec::operator+(Vec& v2) const{
    Vec ret();
    if(mySize>0){
        Vec ret(mySize);
        for(unsigned i = 0;i<mySize;i++){
            ret[i]=v2[i]+myArray[i];
        }
    }
    else{
    }
    return ret;
}

And from the .h file...:

Vec& operator+ (Vec& v2) const;

This throws the error: "invalid initialization of non-const reference of type ‘Vec&’ from an rvalue of type ‘Vec (*)()’" I'm completely new to C++, so any help would be appreciated.

Upvotes: 0

Views: 283

Answers (3)

juanchopanza
juanchopanza

Reputation: 227418

The actual error is that you are declaring a function inside of your operator, instead of declaring a Vec object.

Vec ret();

You can fix that by omitting the ():

Vec ret;

Besides that, you have a fundamental design error in that you are attempting to return a reference to a variable which is local to the scope of your operator, resulting in a dangling reference. The usual way to express an addition operator is to have it return a new object, and is typically implemented as a non-member function with a signature such as

Vec operator+(const Vec& lhs, const Vec& rhs);

This can be implemented in terms of an increment member operator

Vec& operator+=(const Vec& rhs);

This one can return a reference to this hence no dangling reference. An example implementation od operator+ would then be

Vec operator+(Vec lhs, const Vec& rhs)
{
    return lhs += rhs;
}

Upvotes: 3

user213313
user213313

Reputation:

As others have stated your initial declaration of ret which you think is default constructing a Vec is actually forward delcaring a function which takes no arguments and returns a Vec. AKA the most vexing parse.

Also the variable shadowing of 'ret' inside the if statement means that you are not modifying the variable that you are expecting to return. It's likely that you want something more like this:

Vec Vec::operator+(const Vec& v2) const{
    Vec ret(mySize);
    if(mySize>0){
        for(unsigned i = 0;i<mySize;i++){
            ret[i]=v2[i]+myArray[i];
        }
    }
    else{
    }
    return ret;
}

Upvotes: 0

Ed Swangren
Ed Swangren

Reputation: 124652

Vec ret();

Is taken to be a forward declaration of a function which takes no arguments and returns a Vec. See: the most vexing parse.

Next, you're returning a reference to a local variable, which is bad. ret goes out of scope as soon as the function returns.

Upvotes: 7

Related Questions