Daimeon
Daimeon

Reputation: 23

Copy Constructor

Hi im trying to create a copy constructor and im getting a warning. "no suitable constructor found for Money(no arguments) constructor Money.Money(double) is not applicable (actual and formal argument lists differ in length) constructor Money.Money(Money) is not applicable (actual and formal argument lists differ in length)" Im doing this for class and the location where im supposed to create this constructor keeps giving me a warning.

Please help and correct if im wrong.

Here is the task my instructor has given me.

Overload the constructor. The constructor that you will write will be a copy constructor. It should use the parameter Money object to make a duplicate Money object, by copying the value of each instance variable from the parameter object to the instance variable of the new object

This is what ive written.

 public Money(Money object)
   {
       Money newMoney = new Money();
   }

Upvotes: 1

Views: 863

Answers (3)

herokingsley
herokingsley

Reputation: 403

when u create a class, the compiler will add a default constuctor with no arguments like public Money() 2 be ur default constructor.

but after u explicitly define a constructor, the compiler won't do that any more.

so it give a hint that there isn't the applicable (actual and formal argument lists differ in length).

to fix that, u should add the constructor without arguments.

Upvotes: 0

kaitoy
kaitoy

Reputation: 1675

The default constructor (no-argument constructor) is not automatically generated if you define one or more constructor. You defined a constructor with one argument Money(Money object), so you can't do new Money() without explicitly define the no-argument constructor.

BTW, creating a Money object in Money(Money object) is no use. The copy constructor would be like:

public Money(Money object) {
  this.param1 = object.param1;
  this.param2 = object.param2;
}

Upvotes: 2

Benj
Benj

Reputation: 989

when adding a parameterized constructor, the default constructor is removed. try adding

public Money()
   {
   }

to your code. I don't see how your constructor is copying anything though

Upvotes: 2

Related Questions