Copy Constructors vs clone()

In C++, the copy constructor (along with the assignment operator, which doesn't exist in Java) was the standard way of copying an Object. In Java, we have the Clonable interface, but the option of using Copy Constructors remains.
So, which is preferable? The Clonable interface is clumsy and poorly designed, but many programming language theorists discourage the use of Copy Constructors. Bruce Eckel (of Thinking in Java) seems to use Copy Constructors a lot, but Sun uses the Clonable interface.
What are the pros and cons of each?

Hallo,
in order to use the Copy Constructor, you need to know that you have an instance of class X, eg:
X a, b;
a = new X();
b = new X(a);On the other hand, if you are deep in code somewhere and you need a copy of an Object, then cloning is the only way to make a copy, as you do not know what class you have.
doSomething (Object obj) {
   if (obj instanceof Cloneable) {
      Object objCopy = obj.clone();
}So it is a question of horses for courses.

Similar Messages

  • Is java supports Copy Constructor ?

    Is Java Supports copy constructor ? why?
    Thanks

    clone is perferable over copy constructors, as
    Object.clone() will produce the correct type of
    object no matter who called it, wheras you are
    responsible for this if you use copy constructors...
    unless of course the copy constructor is defined in a
    final class, in which case cc's are fine.IMHO, Clone is to be avioded as;
    - most classes don't support it.
    - class which do support it don't do a deep copy which is that most people expect it to do.
    The only really safe way to take a copy of an object is to serialize it and deserialize it.

  • 12.4 beta: private copy constructor in base class required to be called from temporary reference when -g option used

    Hi,
    We've got an abstract base class (StringBase) which various types of strings inherit from. The copy constructor for this base class is private, since we don't want to allow copying when this class shouldn't be directly instantiated. A number of our methods take specify the base class as a reference, but take a derived class temporary as a default argument (see code appended).
    This worked fine in 12.3, but in 12.4 beta, this now says:
       Error: StringBase::StringBase(const StringBase&) is not accessible from __dflt_argA().
    This works fine in clang and gcc, and indeed, this GNU document says it was a bug which was fixed in gcc 4.3.0:
        Copy constructor access check while initializing a reference
    which references http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#391
    It only appears to error when the "-g" option is used, however, which doesn't seem right, and compiles fine if the "-g" option is removed, which makes me think it's a bug. Presumably the optimizer is eliding the copy when not using -g, but it's left in for debug mode, causing the compile error?
    Many thanks,
    Jonathan.
    $ clang++ -std=c++11 defaultarg.cpp
    $ g++ -std=c++11 defaultarg.cpp
    $ /opt/SolarisStudio12.4-beta_mar14-solaris-x86/bin/CC -c defaultarg.cpp
    $ /opt/SolarisStudio12.4-beta_mar14-solaris-x86/bin/CC -g -c defaultarg.cpp
    "defaultarg.cpp", line 6: Error: StringBase::StringBase(const StringBase&) is not accessible from __dflt_argA().
    1 Error(s) detected.
    $ cat defaultarg.cpp
    #include "stringbase.h"
    #include "conststring.h"
    static const ConstString S_DEFAULT("default value");
    void SomeMethod( const StringBase& str = S_DEFAULT )
       (void) str;
    int main( void )
       SomeMethod();
    $ cat stringbase.h
    #ifndef STRINGBASE_H
    #define STRINGBASE_H
    class StringBase
    protected:
       StringBase() {}
    private:
       StringBase( const StringBase& );
    #endif
    $ cat conststring.h
    #ifndef CONSTSTRING_H
    #define CONSTSTRING_H
    #include "stringbase.h"
    class ConstString : public StringBase
    public:
       ConstString() {}
       ConstString( const char* ) {}
       ConstString( const ConstString& );
    #endif

    Thanks for reporting the problem!
    This looks like a compiler bug, I think an artifact of creating a helper function for the debugger for the default argument.
    I have filed bug 18505648 for you.

  • No Pass-by-Value or Copy Constructors

    After having used AS3 for some months now, I've realized that
    there is no pass-by-value option when passing variables into
    functions. The only option is pass-by-reference. Similarly, there
    are no default copy constructors. So, if I want to create a copy of
    an object, I have to write code to create a new instance of the
    object and manually copy all of the source variable's properties to
    the new target object.
    This lack of a pass-by-value mechanism and copy constructors
    leads to some confusing behavior and necessitates writing quite a
    bit of extra code. A common case involving confusion is when a
    function call changes a property of a passed-in object. The caller
    might assume that the object will not be modified and then be
    surprised when it is. This is especially likely to happen when
    different people are working on the caller and the callee. It
    shouldn't be necessary for the caller to be concerned about the
    internal workings of an object being used but, because there is no
    pass-by-value mechanism, the caller often must take this into
    account.
    Because of the lack of a pass-by-value mechanism the onus is
    on the person writing a function to always make a copy of passed-in
    objects if they are going to be modified. Unfortunately, the lack
    of default copy constructors makes this an onerous task. The only
    way to copy an object is to write code to create a new object and
    then copy each property of the object. Where the properties are
    objects themselves a deep copy is needed and the amount of code can
    become large and the task tedious. To do this amounts to writing a
    set of copy constructors for each object and sub-object - each time
    a variable is accessed for modify.
    To make matters worse, it's not even possible to write a copy
    constructor for user-created classes. Consider the following
    attempt at writing a copy constructor to copy two instance
    variables for a custom Form class:
    public function Form(f:Form) {
    this._textHeight = f._textHeight;
    this._actionURL = f._actionURL;
    This causes a "Duplicate function definition" compile error
    because a default constructor already exists.
    Pass-by-value and built-in copy constructors are standard
    features in most OOP languages and their lack in AS3 is a glaring
    omission. I hope Adobe will seriously consider adding them to the
    next version of ActionScript.

    Nitin_Mathur wrote:
    at one time i had doubted my own conceptsNote that the type of a parameter may be different from the type of the object you created. However, it is still the same value that is passed, as pointed out by this example:
    public class Test {
        public Test() {
            //an object of type "MyClass" is created on the heap with the "new" operator:
            MyClass myClass = new MyClass();
            doSomething(myClass);//the reference to the object is passed by value
        private void doSomething(MyInterface myInterface) {
            //the passed value is a reference to a "MyClass" object,
            //but here it is considered to be a "MyInterface" object
            //and we don't have access to the "MyClass"-method "testClass()"
            myInterface.testInterface();
        public static void main(String[] args) {
            new Test();
    interface MyInterface {
        public void testInterface();
    class MyClass implements MyInterface {
        public void testInterface() {
            System.out.println("testInterface");
        public void testClass(){
            System.out.println("testClass");
    }

  • Copy constructor and temporary objects in C++

    I'd need some clarification on how constructor works when the argument is  a temporary object. I defined a dummy MyVect class with operator+ and copy constructor:
    class MyVect {
    public:
    MyVect() {
    cout << "Constructor" << endl;
    MyVect(const MyVect &vect){
    cout << "Copy Constructor" << endl;
    ~MyVect() {
    cout << "Destructor" << endl;
    MyVect operator+(const MyVect &v) const {
    cout << "operator+" << endl;
    MyVect result
    return result;
    Then I test it with this very simple code pattern:
    MyVect v1;
    MyVect v2;
    MyVect v3(v1 + v2);
    The output is:
    Constructor
    Constructor
    operator+
    Constructor
    Destructor
    Destructor
    Destructor
    The first two constructor calls are for v1 and v2, then operator+ for  v1+v2 is called, and  inside it there is a constructor call for result object. But then no copy constructor (nor constructor) for v3 is called. In my limited understanding of C++, I guessed that once the temporary object resulting from v1+v2 has been created, then it would be the argument of the copy constructor call. Instead it looks like the compiler transforms the temporary into v3, since v3 is correctly initialized as the sum of v1 and v2 (I tried with a more complicated version of MyVect to verify this). This behavior reminds me of the move semantics introduced with C++11, but I'm not using the -std=c++11 flag (and in fact if I try to define a move constructor the compilation fails).
    Can anyone please help me to understand what's happening under the hood? Thanks.
    Last edited by snack (2013-02-13 10:44:28)

    wikipedia wrote:The following cases may result in a call to a copy constructor:
    When an object is returned by value
    When an object is passed (to a function) by value as an argument
    When an object is thrown
    When an object is caught
    When an object is placed in a brace-enclosed initializer list
    These cases are collectively called copy-initialization and are equivalent to:[2] T x = a;
    It is however, not guaranteed that a copy constructor will be called in these cases, because the C++ Standard allows the compiler to optimize the copy away in certain cases, one example being the return value optimization (sometimes referred to as RVO).
    Last edited by Lord Bo (2013-02-13 13:58:47)

  • NullPointerException in MimeMessage copy constructor

    It looks like the copy constructor for MimeMessage does not protect against a null flags and as such throws a NullPointerException.
    I'm sure that this boils down to or is triggered by an IMAP server that is in some way not compliant to the IMAP spec.
    I'm wondering if there is a workaround to this that anyone could recommend or if a fix to this is in the works.
    In MimeMessage.getFlags(), it should check to see if flags == null before cloning. If not, it should return a new Flags() would be my guess.
    I saw a discussion in another forum that mentions wrapping MimeMessage and implementing getFlags, however there's no way for my wrapper class to identify whether or not MimeMessages flags are null or not to compensate.
    Any suggestions?

    Yes, your IMAP server is broken. What server (what vendor) is it?
    And yes, JavaMail should better protect against such broken servers.
    I'll fix that for JavaMail 1.4.2.
    In the mean time, something like this should work when you're copying a message:
    public class MyMimeMessage extends MimeMessage {
        public MyMimeMessage(MimeMessage source) {
            super(source);
            if (flags == null)
                flags = new Flags();
    }

  • Copy and Paste clone and healing brush?

    Is it possible to copy clone stamp tool and healing brush effects from one image to another?
    I.e. I edit an image in Lightroom, then work on it in Photoshop CS often using clone and healing brush tool. However, if I then change the original in Lightroom, as I often seem to do, I have to re-do all my work in Photoshop. Is there a way I can copy my Photoshop work from the old to the new image?

    I'm not familiar with CS2 and don't even know whether it has an Options Bar. However, look for Window > Options to see if there is one that just needs enabled.
    Here's what it looks like for Clone Stamp Tool in CS6.

  • Copy/Paste creates clones........

    If I copy (Cmd-C) part of a region and paste it (Cmd-V) somewhere else, it creates a clone of the first region. In fact the clone behavior is sometimes weird like dragging the front of the clip to the right makes the clone rear drag to the left! Glitches aside, is there a way to copy/paste without creating a clone, ie:independant region? I see that it does work by option dragging, however I would prefer to use the first method for multiple fixes. Thanks.

    Same thing happens here. Shouldn´t work that way. I usually use Opt-drag, so I hadn´t noticed this bug before. If it is a bug, that is. If not, a peculiar feature.
    /juhani

  • Copying a bootable clone is okay ?

    I done a bootable clone of my mac, is copying the clone on a another back up drive is okay to keep the clone coy still bootable or not ?

    Cloning it again is OK. Drag-copying it won't produce a bootable system.
    (124404)

  • Constructor question?

    I am working on a class called Firm and it has an array of employee objects as its data field. Its constructor has an array of employee objects as its parameter: it initializes the data field array by copying references from the parameter array in a loop. Its main method creates one or two HourlyEmployee objects and one or more exemptEmployee objects. Then it calls setPay for one HourlyEmployee object and one ExemptEmployee objects and prints the results. Then it calls methods setPay and toString for these two objects (calling println, annotate this part of processing so that the output is readable).
    What I have so far is, Employee being an abstract class that has a Constructor, and methods setPay(), getPay(), and toString. Subclasses HourlyEmployee and ExemptEmployee each with their own constructors and methods getPay() and setPay() along with toString() methods.
    Currently this is what I have for code for my Firm class:
    public class Firm
    private Employee[] empObj;
    Firm(Emp[] empObj)
    for(int i = 0;i<empObj.length;++i)
    arrObj=empObj;
    }Does my constructor have an array of employee objects as its parameters? Do I need to create an Object array[] arrObj?

    if Firm's constructor is being passed an Employee array, then just save that reference.
    public class Firm
      private Employee[] empObj;
      public Firm(Emp[] empObj)
        this.empObj = empObj;
    }Alternatively, you may wish to copy the parameter so that changes to the original (made outside by the guy who passed it to you, for example) don't affect it. In that case, change Firm's constructor to do this:
    this.empObj = new Employee[empObj.length];
    for (int i = 0; i < empObj.length; ++i)
      this.empObj[i] = empObj;
    // or, you may even want to "deep-copy" it like this, if you created
    // a "copy-constructor" or "clone" method:
    this.empObj[i] = new Employee(empObj[i]);
    //or
    this.empObj[i] = (Employee) empObj[i].clone();

  • Is it OK to use clone when you only need shallow copy?

    I created copy contructors for all of my libraries classes because I was afraid of using the clone() method.
    However, my copy constructors create shallow copies of the objects - which is probably the same as using clone().
    Before I go deleting all the copy constructors from all of my classes...
    Is there any reason not to use clone() in this case? Are there any gotchas with clone() when it comes to just a simple shallow copy (perhaps with simple arrays, simple object arrays, or collections) ?
    Thanks

    Another thing worth mentioning is that if you really need to have more control of the clone process, then just over-ride the clone method. In most cases the default Object.clone() method should be enough. BTW don't forget to use the Clonable interface for your class.
    The whole notion of a copy constructor is much more a C++ thing.

  • Cannot copy/paste files from clone of Snow Leopard installation into clean Lion installation.

    I cloned my hard drive onto an external USB drive using disk utility and then erased the internal drive to install Lion onto. 70% of anything I copied from the clone of my 10.6 installation into its new home in Lion just disappeared as soon as I copied it. For example, I copied my old documents folder into its corresponding place in Lion, and the size reduced from ~3.5GB to ~1GB. Does anyone know why this is?
    For obvious reasons, I restored my clone to my internal hard drive using disk utility so I could use 10.6 again, so I can't reasonably do any real troubleshooting until I find time to commit to experimentation. Is this a known bug that will be worked out in 10.7.1?

    2009 with mountain lion isntalled
    The original disc that came with the Mac won't work with Mountain Lion v10.8 installed. Disk repairs are done via the internet using OS X Recovery.
    Since the Mac won't boot, restart while holding down the Command + R keys so you can access the built in utilities to repair the startup disk >  OS X Recovery

  • Cloning a ZFS rooted zone does a copy rather than snapshot and clone?

    Solaris 10 05/08 and 10/08 on SPARC
    When I clone an existing zone that is stored on a ZFS filesystem the system creates a copy rather than take a ZFS snapshot and clone as the documentation suggests;
    Using ZFS to Clone Non-Global Zones and Other Enhancements
    Solaris 10 6/06 Release: When the source zonepath and the target zonepath both reside on ZFS and are in the same pool,
    zoneadm clone now automatically uses the ZFS clone feature to clone a zone. This enhancement means that zoneadm
    clone will take a ZFS snapshot of the source zonepath and set up the target zonepathCurrently I have a ZFS root pool for the global zone, the boot environment is s10u6;
    rpool 10.4G 56.5G 94K /rpool
    rpool/ROOT 7.39G 56.5G 18K legacy
    rpool/ROOT/s10u6 7.39G 56.5G 6.57G /
    rpool/ROOT/s10u6/zones 844M 56.5G 27K /zones
    rpool/ROOT/s10u6/zones/moetutil 844M 56.5G 844M /zones/moetutil
    My first zone is called moetutil and is up and running. I create a new zone ready to clone the original one;
    -bash-3.00# zonecfg -z newzone 'create; set autoboot=true; set zonepath=/zones/newzone; add net; set address=192.168.0.10; set physical=ce0; end; verify; commit; exit'
    -bash-3.00# zoneadm list -vc
    ID NAME STATUS PATH BRAND IP
    0 global running / native shared
    - moetutil installed /zones/moetutil native shared
    - newzone configured /zones/newzone native shared
    Now I clone it;
    -bash-3.00# zoneadm -z newzone clone moetutil
    Cloning zonepath /zones/moetutil...
    I'm expecting to see;
    -bash-3.00# zoneadm -z newzone clone moetutil
    Cloning snapshot rpool/ROOT/s10u6/zones/moetutil@SUNWzone1
    Instead of copying, a ZFS clone has been created for this zone.
    What am I missing?
    Thanks
    Mark

    Hi Mark,
    Sorry, I don't have an answer but I'm seeing the exact same behavior - also with S10u6. Please let me know if you get an answer.
    Thanks!
    Dave

  • Question about variable copying, referencing and LinkedList constructors.

    Is there any advantage in this recommendation?
    "In general, do make sure that you copy mutable arguments and mutable return values when appropriate."
    Now, according to this suggestion:
    public ClassName(LinkedList<String> list)
         this.list = new LinkedList<String>(list);
    Instead of public className(LinkedList<String> list)
         this.list = list;
    }I am confused about the situation where using the copy constructor would be appropriate as opposed to the second method.
    Can someone please explain which would be an ideal situation to use a copy constructor and when to use mere assignment?

    fantastic_ray wrote:
    Is there any advantage in this recommendation?
    "In general, do make sure that you copy mutable arguments and mutable return values when appropriate."If you don't copy mutable arguments and return values, then when you change the state ("contents") of the object, it will be seen by both the original reference and the copy. Sometimes you may want this. Sometimes you may know that no change will occur. You have to judge what's appropriate for your use. In general, though, if there's a chance the elments' states may change, you'll want to copy them.
    >
    Now, according to this suggestion:
    public ClassName(LinkedList<String> list)
         this.list = new LinkedList<String>(list);
    Instead of public className(LinkedList<String> list)
         this.list = list;
    It depends. After you do new ClassName(list), if the code that created the ClassName object is going to keep using the list and you don't want any changes it makes to be seen by the new object and vice versa, then yes, you'd want to do the former.

  • How to clone a user-defined object?

    Hello,
    I need to clone an Object[] array (propArray) that holds objects of Integer, Double, Boolean type, along with objects of user-defined ClassA, ClassB, ClassC type. The matter is that the ClassA object isn't being cloned, while the rest of the user-defined objects are cloned just fine.
    In more detail, ClassA has two properties:
    public class ClassA implements Cloneable{
       private String penaltyFor;
       private Penalty[] penaltyArray;
       protected Object clone(){
          try{
             ClassA o = (ClassA)super.clone();
             o.penaltyFor = this.penaltyFor;
    //         o.penaltyArray = (Penalty[])penaltyArray.clone();  //This ain't working.
             //But neither does this :(.
             int penCount = this.penaltyArray.length;
             o.penaltyArray = new Penalty[penCount];
             for(int i = 0; i < penCount; i++)
                o.penaltyArray[i] = (Penalty)this.penaltyArray.clone();
    return o;
    } catch(CloneNotSupportedException e){ throw new InternalError(); }
    The Penalty class contains properties of primitive type and here is its clone() method:
    public class Penalty implements Cloneable{
       private String penaltyDesc;
       private int lowLimit, upperLimit, penaltyValue;
       protected Object clone(){
          try{
             Penalty o = (Penalty)super.clone();
             o.penaltyDesc = this.penaltyDesc;
             o.lowLimit = this.lowLimit;
             o.upperLimit = this.upperLimit;
             o.penaltyValue = this.penaltyValue;
             return o;
          } catch(CloneNotSupportedException e){ throw new InternalError(); }
       }I don't know what else to try. I suppose the problem is the Penalty[] array, but I may be wrong. An alternative would be to use Copy Constructors, but it will cause too many changes to the code, since the clone() method is used for the propArray copy in many places and the ClassA object is a late addition to the propArray (unfortunately it wasn't planned to exist from the beginning).
    Thank's.

    class ClassA implements Cloneable{
       private String penaltyFor;
       private Penalty[] penaltyArray;
       public Object clone(){
          try{
             ClassA o = (ClassA) super.clone();
             if (penaltyArray!=null){
                o.penaltyArray = (Penalty[]) penaltyArray.clone();
                for(int i = 0; i < penaltyArray.length; i++) {
                    Penalty penalty = this.penaltyArray;
    if (penalty!=null)
    o.penaltyArray[i] = (Penalty) penalty.clone();
    return o;
    } catch(CloneNotSupportedException e){
    throw new InternalError();
    class Penalty implements Cloneable{
    private String penaltyDesc;
    private int lowLimit, upperLimit, penaltyValue;
    public Object clone(){
    try{
    return super.clone();
    } catch(CloneNotSupportedException e){
    throw new InternalError();
    If your Penalties are immutable, you don't need to clone them -- rather,
    make then unclonable, like Strings.

Maybe you are looking for

  • Single Sign On and Application with Web Services

    My Application Server is set as partner application for SSO so for example this address: http://myserver:80 is SSO enabled. I have two ADF applications on it with jspx pages and the ADF security is enabled on them. SSO works for these applications (f

  • COGI error generated while collective order confirmation

    hi ALL, this is the real  task for all PP GURUS. the issue is related with collective order confirmation. client is using customised program ZPP_CONF to confirm the collective order which is based on the sap spro program CORUPROC.this include automat

  • How can I see costs on WBSelement before settlement on definitive asset

    Hi, We have direct investment on WBSelement (posted as statistical value -value type 11- on WBS element). So at order entry, we get for example 100€ on a classe 23 account (asset under construction account in french chart of accounts). When the AuC i

  • Issues with connecting macs with different versions of iphoto

    I connected my iphoto 09 on my macbook pro with my girlfriends iphoto 11 on her macbook pro to transfer some photos. However after I transfered these items to her mac I now find that even though the photos still exist on my mac, iphoto 09 will not op

  • Cloning a test CMS from a Production environment - process?

    Hi there - I am attempting to clone a test environment from a production CMS system database. ENVIRONMENT BO Version: XI3.1 O/S: Linux Web Server: JBOSS 4.3 Database platform: Oracle 10g BOXI SETUP 1. BOXI environment type on Production (clustered wi