Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under what circumstances must I provide, assignment operator, copy constructor and destructor for my C++ class? [duplicate]

Tags:

Say I've got a class where the sole data member is something like std::string or std::vector. Do I need to provide a Copy Constructor, Destructor and Assignment Operator?

like image 654
jjerms Avatar asked Mar 05 '10 11:03

jjerms


People also ask

Under which conditions is it vital to explicitly provide a copy constructor and an assignment operator to a class?

If your class has pointers to other data and need deep copies, or if your class holds a resource that has to be deallocated or has to be copied in a special way.

In what situations a copy constructor is invoked instead of assignment operator?

The compiler provides a copy constructor if there is no copy constructor defined in the class. Bitwise copy will be made if the assignment operator is not overloaded. Copy Constructor is used when a new object is being created with the help of the already existing element.

Under what circumstances does a class's copy constructor execute?

In C++, a Copy Constructor may be called for the following cases: 1) When an object of the class is returned by value. 2) When an object of the class is passed (to a function) by value as an argument. 3) When an object is constructed based on another object of the same class.

When and why we need our own assignment (=) operator in class please explain?

When should we write our own assignment operator in C++? The answer is same as Copy Constructor. If a class doesn't contain pointers, then there is no need to write assignment operator and copy constructor. The compiler creates a default copy constructor and assignment operators for every class.


2 Answers

In case your class contains only vector/string objects as its data members, you don't need to implement these. The C++ STL classes (like vector, string) have their own copy ctor, overloaded assignment operator and destructor.

But in case if your class allocates memory dynamically in the constructor then a naive shallow copy will lead to trouble. In that case you'll have to implement copy ctor, overloaded assignment operator and destructor.

like image 184
codaddict Avatar answered Nov 04 '22 06:11

codaddict


The usual rule of thumb says: if you need one of them, then you need them all.

Not all classes need them, though. If you class holds no resources (memory, most notably), you'll be fine without them. For example, a class with a single string or vector constituent doesn't really need them - unless you need some special copying behavior (the default will just copy over the members).

like image 44
Eli Bendersky Avatar answered Nov 04 '22 08:11

Eli Bendersky