understanding Class

Can someone please explain line 36 and 37 for me?

Why is it necessary to put x.ReturnDay, rather than just having it as ReturnDay?
When I run the program, y.days = 0, and x.Days = 1170. Shouldn't x.Days result in 0 as the class function stated that x is all zero?

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
#include <iostream>
using namespace std;

class Final
{
public:
Final(){

Year = 0;
Month = 0;
Day = 0;
};
Final(int x, int y, int z){
Year = x;
Month = y;
Day = z;
Days = 0;
};
void ReturnDay(Final , Final );

int Days;
private:
int Year;
int Month;
int Day;
};
void Final::ReturnDay(Final A, Final B)
{
Days = 365*(A.Year - B.Year) + 30*(A.Month- B.Month) +
(A.Day - B.Day);
}
int main()
{
Final x;
Final y(3, 2, 15);
x.ReturnDay(y, x);
cout << y.Days<<" "<<x.Days<<endl;
return 0;}
Last edited on
A class is like a form you fill out. You can fill out the same form multiple times and the different copies don't affect each other.

Classes tell you about how to interact with data in memory. This data in memory is called an object, and you can have have multiple objects or even none at all. Variables let you access the objects and classes tell you what the objects look like and how to treat them. Classes do not exist in memory.

An object defined by some class is called an instance of that class. Creating a new object of a class is called instantiating or constructing.
Last edited on
> Why is it necessary to put x.ReturnDay, rather than just having it as ReturnDay?
Because for some reason you said that ReturnDay() was a member function.
Member functions are messages send to an object, so you need to say to which object you are talking to.

> Shouldn't x.Days result in 0 as the class function stated that x is all zero?
You haven't initialized x.Days.
Final x; calls the constructor on line 7, that does not touch this->Days.
Besides you modify x.Days in the `ReturnDay()' function (line 29)
Last edited on
A class is like a general blueprint, and an object is an instance of that blueprint. If you've ever played pokemon, all pokemon have attack, defense, speed, etc... A pokemon is the CLASS. Then an OBJECT of that pokemon class might be Pikachu, or bulbasaur. Kinda nerdy example, but that's what helped me.
ReturnDay changes the Days member of the Final instance that called it. So x.ReturnDay(x,y) changes x.Days. If you called it as y.ReturnDay(x,y) it would change y.Days. You can't just call it as ReturnDay(x,y) because it wouldn't know which Final's "Days" member to change.

Your code assumes that each year is 365 days and each month is 30 days. Obviously this isn't true. If you need an exact answer then you'll have to do something more complicated.
Topic archived. No new replies allowed.