Answer to Question #109539 in C++ for raj

Question #109539
If you need a copy constructor you also need a destructor and operator = why ? we have to just write theory or we have to also write code
1
Expert's answer
2020-04-15T01:54:24-0400

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++.


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS