Hello, I'm having a bit of a problem with a school assignment. The getWeight function seems to return 54 no matter what numbers I use. I've wasted at least 45 minutes trying to figure it out. Here is part of the code. Thanks.
#include "stdafx.h"
#include <iostream>
usingnamespace std;
#include "Dog.h"
Dog::Dog( int h, int w, string n )
: Animal( h, w )
{
setName( n );
metricHeight = h * 2.54;//1 in = 2.54 cm
metricWeight = w / 2.2;
}
string Dog::getName() const
{
return name;
} // end function getName
// function setName definition
void Dog::setName( string n )
{
name = n;
}
// function print definition
void Dog::print() const
{
cout << "This animal is a dog, its name is: "
<< name << endl;
Animal::print();
} // end function print
// return height
int Dog::getHeight() const
{
if ( useMetric( "height" ) )
return metricHeight;
elsereturn Animal::getHeight();
} // end function print
// return weight
int Dog::getWeight() const
{
if ( useMetric( "weight" ) )
return metricWeight;
elsereturn Animal::getWeight();
} // end function getWeight
// function useMetric definition
bool Dog::useMetric( string type ) const
{
int choice = 0;
cout << "Which units would you like to see the "
<< type << " in? (Enter 1 or 2)\n"
<< "\t1. metric\n"
<< "\t2. standard\n";
cin >> choice;
if ( choice == 1 )
returntrue;
elsereturnfalse;
} // end function useMetric
hmmm.... unfortunately with type float I still get 54. By the way it only happens if I get the metric weight from a dog object. Also if I put in a weight of 116 I should get 52 when getting it in metric using integers. 116/2.2 = 52. I think it could also be some bad pointer logic in the main. I'm not particularly sure. Any number I use gives a result of 54
yes. Everything has to be an integer in the program. It's a debugging assignment as well. For the dog when you specify a weight of 116 then ask for the metric it should give 52.
getWeight and getHeight are virtual functions as well. They override the same named functions in the base class. In the base class theyre all just simple get and set
I haven't set it to anything else in the object instantiation, but in that function called in main a setWeight is used. Whatever the weight is set at the getWeight always returns 54 if I get the metric instead of standard
ah thanks! so that means my setWeight is somehow not working in either the base class or the derived class or maybe even the pointers screw it up somehow. I'll take a look.
So I just have to override the setWeight function because when the setWeight is called it only uses the one in the base class and in the base class there is no metric change so the original in the instantiation always stays. Thanks.