Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy constructor Class instantiation

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?

like image 224
Gopi Avatar asked Feb 27 '23 13:02

Gopi


2 Answers

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.

like image 57
Chris H Avatar answered Mar 11 '23 19:03

Chris H


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).

like image 37
danben Avatar answered Mar 11 '23 20:03

danben