Demonstrates use of class member functions. - C++ Class

C++ examples for Class:Member Function

Description

Demonstrates use of class member functions.

Demo Code

#include <iostream>
using namespace std;
#include  <math.h>
const float PI = 3.14159;  // Approximate value of pi.
// A sphere class.
class Sphere/*from   www.  j  a v  a  2  s.c  o m*/
{
   public:
   float r;        // Radius of sphere
   float x, y, z;  // Coordinates of sphere
   Sphere(float xcoord, float ycoord, float zcoord, float radius)
   {
      x = xcoord;
      y = ycoord;
      z = zcoord;
      r = radius;
   }
   ~Sphere()
   {
      cout << "Sphere (" << x << ", " << y << ", " << z << ", " << r << ") destroyed\n";
   }
   float volume()
   {
      return (r * r * r * 4 * PI / 3);
   }
   float surface_area()
   {
      return (r * r * 4 * PI);
   }
};  // End of class.
void main()
{
   Sphere s(1.0, 2.0, 3.0, 4.0);
   cout << "X = " << s.x << ", Y = " << s.y << ", Z = " << s.z << ", R = " << s.r << "\n";
   cout << "The volume is " << s.volume() << "\n";
   cout << "The surface area is " << s.surface_area() << "\n";
}

Result


Related Tutorials