Possible Duplicates:
What is the copy-and-swap idiom?
Copy constructor and = operator overload in C++: is a common function possible?

Is there a way that I can make the body of the copy constructor and assignment operator contain the same code without actually having duplicate code (except for the function headers)?

3

There are 3 best solutions below

12
On

Place the functionality in a separate method and then call that from both your copy constructor and assignment operator code.

Alternatively, you could just call your assignment operator from the copy constructor.

0
On

One common way is the copy-and-swap idiom. You would have to implement a swap operation, but if done correctly, you have the additional benefit of having exception safe assignment.

0
On

Create a function

    init(various parameters you need){
...
//common initializing process
}

then call this function from all you constructors, copy, and assignments operators