Click here to Skip to main content
15,908,444 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was reading something on copy constructors and i saw the code had two copy constructors:
number 1 copy constructor:
Vector::Vector(const Vector& a) : elem{new double[a.sz]}, sz{a.sz} {
for (int i=0; i!=sz; ++i)
elem[i] = a.elem[i];
}


number 2 copy constructor:
Vector& Vector::operator=(const Vector& a) {

double∗ p = new double[a.sz];

for (int i=0; i!=a.sz; ++i)
p[i] = a.elem[i];

delete[] elem;

elem = p;

sz = a.sz;

return ∗this;
}


The problem is that i don't understand why you need the operator= copy constructor when you have the first one. Doesn't that already do the job?. Can you please explain this to me.

What I have tried:

i have tried reading more about copy constructors to find out about this, but i haven't come across any information helping me.
Posted
Updated 24-Oct-21 2:12am

Operator= isn't a constructor - it's an assignment operator: operator overloading - cppreference.com[^]
 
Share this answer
 
Further to OriginalGriff's answer, there is something known as the Rule of 3[^]. It says that if a class implements a destructor, it should also implement a copy constructor and a copy assignment operator. This became the Rule of 5 in C++11, when the move constructor and move assignment operator were added. Those are more for efficiency, but it's a good idea to implement them too.

The rationale for this is that a destructor is usually implemented because an object has resources to free. So if the object is copied, copies of its resources must usually be created too.
 
Share this answer
 
Comments
iwanttoaskquestions 25-Oct-21 4:34am    
oh ok thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900