Invalid Initialization of Non-Const Reference Error in C++

35 views Asked by At

I am re-creating the string class in C++. I developed both the constructor and the copy constructor as well as an operator+ method to concatenate two strings.

The issue I am facing is that the copy constructor is not accepting the rvalue string1 + string2 giving me this error: invalid initialization of non-const reference

here is the parts of the class definition related to the problem.

chaine(chaine &chaine_obj){
    char* str_cpy = new char[chaine_obj.len +1];
    str_cpy[chaine_obj.len] =  '\0';
    this->len = chaine_obj.len;
    for(int i = 0; i < chaine_obj.len; i++){
        str_cpy[i] = chaine_obj.str[i];
    }
    this->str = str_cpy;
}
chaine operator+(chaine &chaine_obj){
    chaine res;
    res.len = this->len + chaine_obj.len;
    char *str_cpy = new char[this->len + chaine_obj.len + 1];
    str_cpy[this->len + chaine_obj.len] = '\0';
    for(int i = 0; i < this->len + chaine_obj.len; ++i){
        if(i < this->len) str_cpy[i] = this->str[i];
        else str_cpy[i] = chaine_obj.str[i-this->len];
    }
    res.str = str_cpy;
    return res;
}

(Combining the two methods):

int main(){
    chaine s1("SALUT");
    chaine s2(" BB");
    chaine s3 = s1 + s2; 
    return 0;
}

Although separating the two methods works just fine even though string1 + string2 is an rvalue and doesn't have an address.

like this :

int main(){
    chaine s1("SALUT");
    chaine s2(" BB");
    chaine s3; 
    s3 = s1 + s2; 
    return 0;
}
0

There are 0 answers