Class Declarations


Syntax

class_specifier:
       class_head { member_list }
 
class_head:
       class_key class_name base_class_spec
       class_key identifier base_class_spec
 
class_key:
       class
       structure
       union

Notes

Examples

struct point_A {int x; int y;}; // point_A is structure, therefore x and y are public
 
point_A point_A1, point_A2;    // declares two instances of point_A
point_A1.x = point_A1.y = 0;   // updates the members of point_A1 - which are public
 
class point_B    // members of point_B explicity set to public
{                // the default access of a member of a class is private
 public:         // however the 'public' access specifier
  int x;         // causes subsequent member declarations to be public
  int y;
};
 
class point_C {int x; int y;} point_C1; // members of class point_C are private - defines an instance as well
point_C1.x = point_C1.y = 0;            // syntax Error ! x and y are private.
 
struct{int x; int y;} point_D;          // no class name but declares an instance
 
class point_E                           // this class has methods!
{
 int x;                                 // members x and y are private.
 int y;
 
 public:
 
 point_E(int x_set, int y_set)          // constructors and other methods are public
  : x(x_set), y(y_set) {}               // member initialization syntax copies constructor params

 point_E(const point_E& point_copy)     // this is a copy constructor.
  : x(point_copy.x), y(point_copy.y) {}
 
 point_E& operator=(const point_E& point_assign)  // this is an assignment operator.
  {x = point_assign.x; y = point_assign.y; return *this;}
 
 int& operator()(int index)  // matrix like access to members
  {return index == 0 ? x : y;}
};
 
point_E point_origin(0,0);
point_E point_test = point_origin;   // note that copy constructor is called here !
point_test(0) = point_test(1) = 1;   // matrix index like operator
point_test = point_origin;           // assignment operator called here