Destructors and Constructors

Hey, so i wrote this DATE class and I'm still new to programming and really just do not understand the concept of Destructors and constructors. I'm supposed to be able to write a destructor and a copy constructor for the following code. I need some help.

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
 class Date
 {
 
private:
 
int month;
 
int day;
 
int year;
 
public:

 
Date()
 
{ 
month=1;
 day=1;
 year=1970;}
 
Date(int m, int y)
 
{ 
month=m;
 day=1;
 year=y;
 
}
 
Date(int m, int d, int y)
 
{
 month=m;
 day=d;
 year=y;
 
}

 int getMonth()
 
{return month;}
 

int getDay()
 
{return day;}
 
int getYear()
 
{return year;}
 

void setmonth(int m)
 
{month=m;}

 
void setDay(int d)
 
{day=d;}

 void setYear(int y)
 
{year=y;}

 void printDate()
 
{
 cout<<month<<"/"<<day<<"/"<<year;
 
}
 
};
You need not to define explicitly the destructor for this class as and the copy constructor. You may be satisfied with the destructor and the copy constructor implicitly defined by the compiler.
Alright, your indenting is making me twitch, so I've fixed that up for you :p
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Date
{ 
    int month;
    int day;
    int year;
 
    public:
        Date()
        { 
            month = 1;
            day = 1;
            year = 1970;
        }
        Date(int m, int y)
        { 
            month = m;
            day = 1;
            year = y;
        }
        Date(int m, int d, int y)
        {
            month = m;
            day = d;
            year = y;
        }

        int getMonth() { return month; }
        int getDay() { return day; }
        int getYear() {return year;}
 
        void setmonth(int m) { month = m; }
        void setDay(int d) { day = d; }
        void setYear(int y) { year = y; }
        
        void printDate() 
        {
            std::cout << month << "/" << day << "/" << year;
        }
};

You don't need to put private: unless you put the private stuff after the public stuff, as the default for a class is private.

Vlad is correct, you don't need to define a copy constructor because the default one will do exactly what you would need it to do (copy the fields as they are). Same goes with the default destructor. unless you wish to have the class say something when it gets destroyed. in that case:
1
2
3
4
~Date()
{
     std::cout << "Goodbye cruel world!" << std::endl;
}

if you really wish to make a copy constructor, then here you go:
1
2
3
4
5
6
Date(const Date& date)
{
    month = date.month;
    day = date.day;
    year = date.year;
}
Last edited on
Topic archived. No new replies allowed.