Need help using a constructor to pass in parameters for a templated class

Fixed
Last edited on
Fixed
Last edited on
closed account (Dy7SLyTq)
a) why make it take a template if your going to "hard code" floats?
b) have you tried using *this?
1
2
3
4
5
6
7
8
9
10
11
  Rectangle (float a, float b)
  {
    length = a;
    width = b;
  }
  
  void setLength(const float& length);
  float getLength() const {return side;}

  void setWidth(const float& width);
  float getWidth() const {return side;}

Lines 8 and 11.
Fixed
Last edited on
1
2
3
4
5
6
template <class DataType>
void Rectangle<DataType>::setLength(const float& length)
{
  //side = length*2;
  this->length = length*2;
}


It is necessary to use this-> here to specify the correct length variable since you gave the parameter the same name as the member variable (which causes the parameter name to hide or "shadow" the data member with the same name.)

Or, if you prefer:

1
2
3
4
5
template <class DataType>
void Rectangle<DataType>::setLength(const float& len)
{
  length = len*2;
}


But, I'm not sure sure why you're multiplying by 2 here. After all length isn't named doubleLength.
Last edited on
Topic archived. No new replies allowed.