• Welcome to Jose's Read Only Forum 2023.
 

ProgEx27 - Add Mutators/Accessors To Our Class

Started by Frederick J. Harris, November 09, 2009, 01:26:52 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Frederick J. Harris


/*
  ProgEx27   C++ Classes

  In this further enhanced version of the Box class we've added mutators or
  accessors in the form of Get/Set functions to act on the private member
  variables.  In these accessors you can enforce whatever validation scheme
  makes sense in terms of the functionality and integrity of the class.  In the
  case below I decided negative dimensions don't make sense, so I added an if
  statement to ensure all values are greater than or equal to zero.
*/

#include <stdio.h>

class Box
{
public:
Box()   //Box Uninitialized Constructor
{
  printf("Box Constructor Called!\n");
}

Box(double dblLength, double dblWidth, double dblHeight)
{
  printf("Called Box Fully Initialized Constructor!\n");
  m_Length=dblLength;
  m_Width=dblWidth;
  m_Height=dblHeight;
}
     
~Box()  //Box Destructor
{
  printf("Box Destructor Called!\n");
}

double Get_Length()
{
  return m_Length;
}

void Set_Length(double dblLength)
{
  if(dblLength>=0)
     m_Length=dblLength;
}

double Get_Width()
{
  return m_Width;
}

void Set_Width(double dblWidth)
{
  if(dblWidth>=0)
     m_Width=dblWidth;
}

double Get_Height()
{
  return m_Height;
}

void Set_Height(double dblHeight)
{
  if(dblHeight>=0)
  m_Height=dblHeight;
}

double Volume()
{
  return m_Length*m_Width*m_Height;
}

private:
double m_Length;
double m_Width;
double m_Height; 
};   

int main(void)
{
Box bx1(2.0,3.0,4.0);
Box bx2;

bx2.Set_Length(3.0);
bx2.Set_Width(4.0);
bx2.Set_Height(5.0);
printf("bx1.Volume()     = %f\n",bx1.Volume());
printf("bx2.Volume()     = %f\n",bx2.Volume());
printf("bx1.Get_Length() = %f\n",bx1.Get_Length());
printf("bx1.Get_Width()  = %f\n",bx1.Get_Width());
printf("bx1.Get_Height() = %f\n",bx1.Get_Height());
getchar();   
   
return 0;   
}

/*  --Screen Output--
Called Box Fully Initialized Constructor!
Box Constructor Called!
bx1.Volume()     = 24.000000
bx2.Volume()     = 60.000000
bx1.Get_Length() = 2.000000
bx1.Get_Width()  = 3.000000
bx1.Get_Height() = 4.000000
*/