Do constructors need to take arguments?

1. I found the example below online and I had a question about the constructor. What if it was just simply Date() and it took no arguments? Or what if it was simply Date(int nMonth,int nDay, int nYear). Do constructors have to take arguments?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 
class Date
{
private:
    int m_nMonth;
    int m_nDay;
    int m_nYear;
 
public:
    Date(int nMonth=1, int nDay=1, int nYear=1970) //Constructor
    {
        m_nMonth = nMonth;
        m_nDay = nDay;
        m_nYear = nYear;
    }
};
 
int main()
{
    Date cDate; // cDate is initialized to Jan 1st, 1970 instead of garbage
 
    Date cToday(9, 5, 2007); // cToday is initialized to Sept 5th, 2007
 
    return 0;
}
Last edited on
Constructors are just special functions with no return type. You can overload constructors just like you can overload functions. You can decide how many and what kind of arguments your constructors take.
When calling this you wont need to enter any parameters because these are declared as default parameters. But you can change the value in ascending order of params .

Default parameter (yep not only for constructor)
You have to put them at the end of the param list .

Default contructor , unless you delete it , unless you implement it , the compiler will create it for you. Including constructor , assignment operator and copy constructor. Something the compiler wont create the assignment operator ...
Topic archived. No new replies allowed.