Yongwei Xing
Yongwei Xing

Reputation: 13441

Only implement copy constructor, no assignment constructor

When the class with a member which is a pointer, we need implement a copy constructor for it. I have a question, if we have implemented a copy constructor, should we implement an assignment constructor too?

Best Regards,

Upvotes: 0

Views: 293

Answers (3)

Pardeep
Pardeep

Reputation: 949

Whenever a class has a member variable to which memory is dynamically allocated, one should always implement following

  1. Copy Constructor
  2. Assignment Operator
  3. Destructor

Note : If the pointer variable is static, then no need to have all these.

Upvotes: 0

SadSido
SadSido

Reputation: 2551

Another option here is using some smart pointer, appropriate to your tasks. By choosing the right smart pointer you can rely on compiler-generated destructor, copy constructor and an assignment operator (and write none of your own)...

Upvotes: 2

It is not called an assign constructor but rather an assignment operator, and yes you should. The rule of thumb is: if you need to write a destructor then you should also provide a copy constructor and assignment operator (or block the compiler from generating one)

Upvotes: 10

Related Questions