When copy constructor is created, you need assignment operator and destructor. This is in C++ language called - "The rule of three".
It's always needed when your class managing some resources.
Copy constructor is responsible for copy data from already created object in initialization state. For example:
A obj{}; <= new object of user type A
A new_obj(obj) <= here is used copy constructor, copy data from obj to new_obj
Assigment operator is used when objects already created and you assign one to another one. For example:
new_obj = obj; <= here is used assigment operator, copy data from obj to new_object
And destructor is used for correct removing object, for example if you have pointer to allocated memory. In destructor you need deallocate it.
~A()
{
delete pointer;
}
Without one of this methods, most likely you will get a lot of errors. So “The rule of three” it’s a good practice in C++.
Comments
Leave a comment