Demonstrates use of overloaded constructors. - C++ Class

C++ examples for Class:Constructor

Description

Demonstrates use of overloaded constructors.

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 w ww . ja  v  a  2  s. com*/
{
   public:
   float r;        // Radius of sphere
   float x, y, z;  // Coordinates of sphere
   Sphere() { /* doesn't do anything... */ }
   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";
   }
   inline float volume()
   {
      return (r * r * r * 4 * PI / 3);
   }
   float surface_area()
   {
      return (r * r * 4 * PI);
   }
};
void main()
{
   Sphere s(1.0, 2.0, 3.0, 4.0);
   Sphere t;    // No parameters (an uninitialized sphere).
   cout << "X = " << s.x << ", Y = " << s.y << ", Z = " << s.z << ", R = " << s.r << "\n";
   t = s;
   cout << "The volume of t is " << t.volume() << "\n";
   cout << "The surface area of t is " << t.surface_area() << "\n";
   return;
}

Result


Related Tutorials