views:

99

answers:

5

Hi

Here is my class that implements copy constructor

public class TestCopyConst
{
    public int i=0;
    public TestCopyConst(TestCopyConst tcc)
    {
       this.i=tcc.i;
    }
}

i tried to create a instance for the above class in my main method

TestCopyConst testCopyConst = new TestCopyConst(?);

I am not sure what i should pass as parameter. If i have to pass a instance of TestCopyConst then again i have to go for "new" which in turn will again prompt for parameter

TestCopyConst testCopyConst = new TestCopyConst(new TestCopyConst(?));

what is missing here? or the concept of copy constructor is itself something different?

+4  A: 

You're missing a constructor that isn't a copy constructor. The copy constructor copies existing objects, you need another way to make them in the first place. Just create another constructor with different parameters and a different implementation.

Chris H
+2  A: 

You need to also implement a no-arg constructor:

public TestCopyConst()
    {

    }

Or one that takes an i:

public TestCopyConst(int i)
    {
        this.i = i;
    }

Then, you can simply do this:

TestCopyConst testCopyConst = new TestCopyConst();

Or this:

TestCopyConst testCopyConst = new TestCopyConst(7);

Normally, your class will have a default no-arg constructor; this ceases to be the case when you implement a constructor of your own (assuming this is Java, which it looks like).

danben
A: 

You would use a Copy Constructor as an overloaded constructor to clone an object, but you also need another constructor to initialize an instance in a normal way:

public class TestCopyConst
{
    public int i=0;

    public TestCopyConst(int i)
    {
       this.i = i;
    }

    public TestCopyConst(TestCopyConst tcc)
    {
       this.i=tcc.i;
    }
}
Mark Seemann
A: 

You need

public class TestCopyConst 
{ 
    public int i=0; 
    public TestCopyConst(TestCopyConst tcc) 
    { 
       this.i=tcc.i; 
    } 
    public TestCopyConst(int val)
    {
       i = val;
    }
    //or
    public TestCopyConst()
    {
    }
} 
astander
A: 

'the concept of copy constructor is itself something different?'

Java doesn't have copy constructors in the way C++ has them, i.e. that are automatically generated and/or called by the compiler. You can define one yourself but it only has a use if you call it. Not the same thing, by a long chalk.

I am not sure what i should pass as parameter. If i have to pass a instance of TestCopyConst then again i have to go for "new" which in turn will again prompt for parameter

Here you are proving the point. The only thing you can pass to a copy constructor is another instance of the same class (or derived class...). If you don't have another instance to copy, why do you think you need a copy constructor at all?

EJP
Regarding the second point, i was just trying to experience the copy constructor to know what its was exactly.
Sri Kumar
Well it isn't anything in Java so forget about it.
EJP