• Welcome to Jose's Read Only Forum 2023.
 

ProgEx26 - Add A Few More Members To Our Simple Class

Started by Frederick J. Harris, November 09, 2009, 01:25:15 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Frederick J. Harris


/*
  ProgEx26   C++ Classes

  In the program below we've added two member functions to the class Box. 
  We've added another Constructor and a function Volume() to return the volume
  of a Box instance.  Note that we now have two member functions named Box.
  The first has a void parameter list and the other has a parameter list
  comprised of the three dimensions of a box.  They are both termed Constructors
  because they have the same exact name as that of the class.  They are also
  overloaded functions as we described several ProgExs back because they have
  the same name.  Constructors in classes can be overloaded and usually are
  to facilitate the construction of objects in different ways. 
*/

#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()  //CBox Destructor
{
  printf("Box Destructor Called!\n");
}

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

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

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

printf("bx1.Volume() = %f\n",bx1.Volume());
getchar();   
   
return 0;   
}

/*  --Screen Output--
Called CBox Fully Initialized Constructor!
bx.Volume() = 60.000000
*/