C++ Class Constructor

Special method to create instance of a class, typically initializes class variables.

Class with a constructor

class date
{
  
     int day, //internal storage scheme
                  month, //this is private to the class
         
year;

   char *message; //string message reflecting date

   public:
     void new_date(int,int,int); //method to change the date

          char* give_date(); //report date

          date(int); //constructor to set day only

};

Now define the methods

date::date(int d)
{
   day = d;

}

void date::new_date(int d, int m, int y)
{
   day = d;
   month=m;
   year=y;
}

void date::give_date()
{
   char *buf= new char[80];

   sprintf(buf, "%s %d, %d", mname[month],day,year);


   return buf;
}

 

Create an instance of the class

date d(29); //will call constructor passing day of month

Rules of Constructors

  1. A constructor cannot return a function value, and has no return value type.
  2. A class may have several constructors. The compiler chooses the appropriate constructor by the number and types of parameters used.
  3. Constructor parameters are placed in a parameter list in the declaration of the class object.
  4. The parameterless constructor is the default constructor.
  5. If a class has at least one constructor, and an array of class objects is declared, then one of the constructors must be the default constructor, which is invoked for each element in the array.