Difference between copy constructor and assignment overload in C++

copy constructor is called when an object is created while assignment overload is called when an object has been created.

For example

#include <iostream>
using namespace std;

class OBJ
{
public:
    OBJ(){}
    OBJ(OBJ &obj2){
        cout<<"copy constructor"<<endl;
    }
    void operator = (OBJ& obj2){
        cout<<"assignment overloading"<<endl;
        
    }
};
int main()
{
    OBJ ob1;
    OBJ ob2=ob1;  //output "copy constructor"
    OBJ ob3(ob1); //output "copy constructor"
    OBJ ob4; 
    ob4=ob1;      //output "assignment overloading"
    return 0;
}

 

posted on 2013-05-18 14:53  bian  阅读(186)  评论(0编辑  收藏  举报

导航