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