Topic : Introduction to C++ Classes
Author : Jonah
Page : << Previous 2  
Go to page :


  }

    void setYear(int y)
    {
      if (y < 1900) return;  // Out of range
      year = y;
    }
  };


The final topic that this introductory tutorial will cover is constructors. A constructor is a member function (though it has no return type) that contains the same name as the class. It can optionally take arguments which can be used to set initial values for the class. When an instance is created, a constructor is called to initialize all the data in the class. In C and C++, when datatypes are allocated their value is simply whatever garbage is already in memory at the time. Thus, the constructor ensures that every instance is initialized with a valid value.


  class date
  {
  private:
    int day;
    int month;
    int year;

  public:
    bool validDate(int d, int m, int y)
    {
      if (d < 1 || d > 31) return 0;
      if (m < 1 || m > 12) return 0;
      if (y < 1900) return 0;

      return 1;
    }

    date()  // Default constructor
    {
      day = 1;
      month = 1;
      year = 1999;
    }

    date(int d, int m, int y)  // Constructor taking initial date values
    {
      if (validDate(d, m, y))
      {
        day = d;
        month = m;
        year = y;
      }
      else
      {
        date();  // Call constructor to set default values
      }
    }
  };


The first constructor initializes each date object to January 1st, 1999. This constructor, which takes no parameters, is called automatically if the user doesn't specify any arguments, and parenthesis may also be omitted. The second one takes the initial day, month, and year as parameters. However, it only sets them to the date instance if they are within the valid range as specified by validDate:



  date birthday;  // January 1st, 1999
  date anniversary (14, 12, 1986);  // December 14th, 1986

  date yesterday (39, 4, 1450);  // Out of range.  Set to January 1st, 1999


This tutorial has covered the following key concepts of C++ classes:

1.Object-oriented programming - Data is grouped together with the functions that act on it.
2.Private data - Data members remain private. All modification is through functions.
3.Accessors and modifiers - Both public member functions. Accessors return the value of private data members. Modifiers validate and change the values of the private data members.
4.Constructors - Functions called when instances are first created to initialize the private data members of the class.

Page : << Previous 2