user1527227
user1527227

Reputation: 2238

How to set a default constructor when there's more than one

I'm learning about constructors in C++ and I understand that you can declare more than one constructor. You can see below that I have 2 Date constructors below, but I want to set Date(long) as the default one. Can someone please explain how I would do this?

Ok so apparently the question above makes so sense. I am working a problem from the book and this is what it says:

Modify Program 10.3 so that the only data member of the class is a long integer named yyyymmdd. Do this by substituting the declaration long yyyymmdd; for these existing declarations:

int month; int day; int year;

Using the same constructor prototypes currently declared in the class declaration section, rewrite them so that the Date(long) method becomes the default constructor, and the Date(int, int, int) method converts a month, day, and year into the correct form for the class data members.

Program 10.3:

#include <iostream>
#include <iomanip>
using namespace std;

class Date
{
    private:
        int month, day, year;
    public:
        Date(int=7, int=4, int=2012);
        Date(long);
        void showDate();
};

Date::Date(int mm, int dd, int yyyy)
{
   month = mm;
   day = dd;
   year = yyyy;
}

Date::Date(long yyyymmdd)
{
    year = int(yyyymmdd/10000);
    month = int( (yyyymmdd - year*10000)/100);
    day = int(yyyymmdd - year*10000 - month*100);
}

void Date::showDate()
{
    cout << "The date is "
         << setfill('0')
         << setw(2) << month << '/'
         << setw(2) << day << '/'
         << setw(2) << year % 100;
    cout << endl;
}

int main()
{
    Date a;
    Date b(4,1,1998);
    Date c = Date(20090515L);

    a.showDate();
    b.showDate();
    c.showDate();
    return 0;
}

Upvotes: 1

Views: 2549

Answers (2)

king_nak
king_nak

Reputation: 11513

You cannot set a default constructor. Per definition, the default constructor is the constructor that can be invoked without arguments.

It is automatically used if you do not (or cannot) specify arguments when creating an object.

For example if you define an array of objects, all of those objects will be constructed using the default constructor:

Date dates[5]; // Will create 5 Dates using Date::Date(7, 4, 2012)

Upvotes: 1

Mark B
Mark B

Reputation: 96251

The default values for the month/day/year constructor you have make it the default constructor (you can call it with no parameters. What you want to do is un-default those and default the parameter to the long constructor:

    Date(int, int, int);
    Date(long = 20120704);

Upvotes: 3

Related Questions