operator overloading

So I put together a program and I am wondering why this program doesn't run if I omit a piece of code which I post below.

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
#ifndef CAT_H
#define CAT_H


class Cat
{
    public:
        Cat();
        Cat(int);
        void getCount();
        void print();
        Cat operator-(const Cat &object);
    private:
        int total;
};

#endif // CAT_H

#include <iostream>
#include "Cat.h"

using namespace std;

Cat::Cat()
{

}

Cat::Cat(int t)
{
    total = t;
}

void Cat::getCount()
{
    cin >> total;
}

void Cat::print()
{
    cout << "Total cats: "<<total << endl;
}

Cat Cat::operator-(const Cat &object)
{
    return total - object.total;
}

#include <iostream>
#include "Cat.h"

using namespace std;

int main()
{
    Cat object;
    object.getCount();

    Cat obj2;
    obj2.getCount();

    Cat obj3;
    obj3 = object - obj2;
    obj3.print();
}


When I omit this function the program doesn't work.

1
2
3
4
Cat::Cat(int cat)
{
    total = t;
}


It also doesn't work when I switch the code to this.

1
2
3
4
Cat::Cat(int t)
{
    t= total;
}



Can someone explain why this piece of code is necessary and why it has to be arranged in that way?

I made this program for the purpose of learning.
Last edited on
return total - object.total; the result of this operation is an integer type. Your overloaded - operator returns type Cat. Which means the integer needs to be converted to type Cat. The compiler does this by looking in the Cat class for a constructor that takes an integer parameter. It can then use this constructor to create on object of type Cat from the integer. This is called automatic type conversion.
Thanks Yanson. I understand now.
Topic archived. No new replies allowed.