I have a class Graph and I need a copy of that graph. I am going to modify the internals of graph object ( eg: delete an edge etc. ). I have 2 ways to implement a graph.
- A copy constructor
- A method called 'getGraph() { return new Graph(this)}'. This method getGraph can do a defensive copy.
The only advantage of copy constructor, from my understanding is copy-at-will. This means if I dont want to modify graph object, there is not need for 'getGraph' to do a defensive copy.
Now coming back to my question.
- Is it better to use a copy constructor or is it better to use a function which returns copy of self object ?
- Why ?
As far I understand your question
In copy constructor you would do something like
and in getGraph() you would do
I suggest make your Graph class implement
Cloneable
interface and overrideclone()
method to get a deep copy you need.