简体   繁体   中英

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

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.

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..

I recommend this Question Because explain the const and non-const variable. It's because explain this error:

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

C++ alow this, because it's initialization:

int main(){
    Test x=6;//initialization "const Test& obj = 6" OK
}

But C++ doesn't allow this(non-const value):

int main(){
    Test x=6;//initialization "Test& obj = 6" Not Ok!
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM