Home > Net >  Assignment operator is not calling parameterized constructor while copy constructor present in code
Assignment operator is not calling parameterized constructor while copy constructor present in code

Time:10-05

CASE 1: When I create a object of class with an assignment operator , it calls parameterized constructor if there in no copy constructor in code.

Below code is without copy constructor:

class Test{
    public:
    int a;
    Test(int a){
        this->a = a;
    }
};
int main(){
    Test x = 6;
    cout<<x.a;
    return 0;
}

CASE 2: But if there is copy constructor present in class then it gives error if I use assignment operator while declaring class object.

Error : cannot bind non-const lvalue reference of type ‘Test&’ to an rvalue of type ‘Test’

Below code is with copy constructor

class Test{
    public:
    int a;
    Test(int a){
        this->a = a;
    }
    Test(Test &b){
       this->a = b.a;
    }

};
int main(){
    Test x = 6;
    cout<<x.a;
    return 0;
}

My question is how just presence of copy constructor is result ending up with error ? . With presence of copy constructor also my program should call Parameterize constructer when I assign a parameter to object of class.

CodePudding user response:

I think this:

Test(Test &b){
   this->a = b.a;
}

Should actually be this:

Test(Test const &b){
   this->a = b.a;
}

Copy constructor should get a const reference, and they should copy the parameter content into the current object content, not the other way around..

  • Related