why we need copy constructor & assignment operator

 

When we study the C++, please think more about the mechanism or the reason why the grammar is needed.

The base it based on is the essential to this language.

 

Q: why we need copy constructor & assignment operator   ##Answer is from http://www.codeproject.com/Questions/205205/Why-we-need-the-Copy-Constructor-the-Assignment-Op

 

I Think was explained lot of times in CP.But not by me so i am taking this one,
A copy constructor is a special constructor that initializes a new object from an existing object.Compiler will creates a default copy constructor which copies your class data bit by bit, if you wont create it.Then why we have to re-create a Copy constructor?consider this class(not a professional code).

Class A
{
    public int *p;
    A(){ p = new int;}
    ~A(){
         delete p;
     }
};
int main()
{
   A a;
   A b = a; //default copy constructor provided by compiler,which exactly copies a.p pointer to to b.p;
   return 0;
};
But there is one big problem.when main is going to die,it will clean all stack variables.So may be first "a" destructor will be called and "a.p" is deleted.Next b destructor will be called,which again tries to delete b.p which is already deleted in a(Note thst a.p and b.p pointes same pointer).This will cause an run time error.To overcome this problem we have to create a copy aonstructor and Assignement operator(which is called in different scenarios).So the Class A copy constructor will be,
class A::A(const class A& RefA)
{
   p = new int;    // create a new p 
   *p = *RefA.p; // copy the value
}
So now both a, b in the above example will have different p pointers.Assignement operator functionality is also same.But there aim is defferent.

There are three general cases where the copy constructor is called instead of the assignment operator:
1. When instantiating one object and initializing it with values from another object (as in the example above).
2. When passing an object by value.
3. When an object is returned from a function by value.

In other cases like,
A a;
a = b; 
an Assignment operator is called
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值