Constructor Overloading Code for C++

This program show how to create an Overloaded Constructor in a C++ program. The Constructor is declared in the class date and later defined outside the class. The class date consists of three Integer variables which contain the day, month and year of the date wished to be stored. There are two constructors defined with different Signatures i.e. one is using String and the other using the three Integer values, one for each of month, date and year.


The first constructor defined uses the sscanf() function to retrieve the values of month, day and year. The sscanf() function basically reads formatted text from a source of String. The String passed on to the function is checked for the datatypes specified in the sscanf() parameter. These values are then saved to the specified locations i.e. variables namely day, month and year. This is an alternate way to reading from a scanf().


#include <iostream.h>
#include <stdio.h>
#include <conio.h>

class date
{
      int day, month, year;
      public:
      date(char *d);
      date(int m, int d, int y);
      void show_date();
};
// Constructor Initialize using string.
date::date(char *d)
{
      sscanf(d, "%d%*c%d%*c%d", &month, &day, &year);
}

// Constructor Initialized using integers.
date::date(int m, int d, int y)
{
      day = d;
      month = m;
      year = y;
}
void date::show_date()
{
      cout << month << "/" << day;
      cout << "/" << year << "\n";
}

int main()
{
      clrscr();
      date ob1(12, 4, 2001), ob2("10/22/2001");
      ob1.show_date();
      ob2.show_date();
      getch();
      return 0;
}

Constructors are overloaded just as in the same way you would overload other functions. The difference between functions and constructors is that constructors do not have a return type and are primarily used to initialize class variables.

No comments:

Post a Comment

Custom Search