Nikhil Shah
Nikhil Shah

Reputation: 3

How to fix main function calling the incorrect function when passing parameters? (c++)

I have a project for my CS class and I have written a copy constructor and am passing an object of the class into it, but the main is calling the wrong constructor.

main:

Mammal x;
cout << "Initial values for x: ";
cout << "Age = " << x.getAge() << " Weight = " << x.getWeight() << endl;
x.setAge(10);
x.setWeight(123);
cout << "Modified values for x: ";
cout << "Age = " << x.getAge() << " Weight = " << x.getWeight() << endl;
Mammal w(&x);
cout << "\nModified values for w: ";
cout << "Age = " << w.getAge() << " Weight = " << w.getWeight() << endl;
w.sound();

copy constructor:

Mammal(Mammal &x)
{
    this->canSwim = x.canSwim;
}

function the main is calling:

 Mammal(bool x)
{
    canSwim = x;
}

I expect the output to copy the values, but it sets the value of age and weight to 0 from the default constructor.

Upvotes: 0

Views: 77

Answers (2)

Jeffrey Cash
Jeffrey Cash

Reputation: 1073

When you pass by reference, you do not use & to get the address of something.

Try the following:

Mammal w(x);

Also, I suggest using the compilation flags -Wall -Wextra, as they would likely have alerted you to this issue.

Upvotes: 2

marcelodmmenezes
marcelodmmenezes

Reputation: 221

Your copy constructor is only copying the canSwim attribute. You must explicitly tell what attributes you want to copy:

Mammal(Mammal &x)
{
    this->canSwim = x.canSwim;
    this->age = x.age;
    this->weight = x.weight;
    ...
}

And as pointed out by @Jeffrey Cash, you should remove the "&" from the constructor call.

Upvotes: 0

Related Questions