What is a class? Well, that's a struct yet with more possibilities.


METHODS can be defined. They are C++ functions dedicated to the class.

Here is an example of such a class definition:

#include <iostream.h>

class vector
{
public:

   double x;
   double y;

   double surface ()
   {
      double s;
      s = x * y;
      if (s < 0) s = -s;
      return s;
   }
};

void main(void)
{
   vector a;

   a.x = 3;
   a.y = 4;

   cout << "The surface of a: " << a.surface() << endl;
}




In the example above, a is an INSTANCE of the class "vector".
Just like a function, a method can be an overload of any C++ operator,
have any number of parameters (yet one parameter is always implicit:
the instance it acts upon), return any type of parameter, or return no
parameter at all.

A method is allowed to change the variables of the instance it is acting upon:




#include <iostream.h>

class vector
{
public:

   double x;
   double y;

   vector its_oposite()
   {
      vector r;

      r.x = -x;
      r.y = -y;

      return r;
   }

   void be_oposited()
   {
      x = -x;
      y = -y;
   }

   void be_calculated (double a, double b, double c, double d)
   {
      x = a - c;
      y = b - d;
   }

   vector operator * (double a)
   {
      vector r;

      r.x = x * a;
      r.y = y * a;

      return r;
   }
};

void main (void)
{
   vector a, b;

   a.x = 3;
   b.y = 5;

   b = a.its_oposite();

   cout << "Vector a: " << a.x << ", " << a.y << endl;
   cout << "Vector b: " << b.x << ", " << b.y << endl;

   b.be_oposited();
   cout << "Vector b: " << b.x << ", " << b.y << endl;

   a.be_calculated (7, 8, 3, 2);
   cout << "Vector a: " << a.x << ", " << a.y << endl;

   a = b * 2;
   cout << "Vector a: " << a.x << ", " << a.y << endl;

   a = b.its_oposite() * 2;
   cout << "Vector a: " << a.x << ", " << a.y << endl;

   cout << "x of oposite of a: " << a.its_oposite().x << endl;
}




Added on June 16, 2007 Comment
}