Over Loading Operators!

Hi, I just learned overloading operators and I have questions. For instance here is the overload operator I wrote.

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

class box{

public:
	box(int=0,int=0,int=0);

	double volume(){
	return l*h*w;	
	};

	void operator>(box a);

private:
	double h;
	double l;
	double w;

};
box::box(int a,int b,int c){
	h=a;
	l=b;
	w=c;
}
void box::operator>(box a){

	if (a.volume() > volume())
		cout<<"The object passed is greater with volume: "<<a.volume()<<endl;
	else
		cout<<"The object passed is not greater with volume: "<<a.volume()<<endl;
}

int main(){

	//Question #2
	box x(1,2,3), g;
	box f(7,8,120), m(8,6,4);
	cout<<"Comparing two objects: "<<endl;
	g>x; 
	cout<<endl;
	m>f;

	return 0;

}


Questions:
Which object is being passed to the overload operator ? g or x , m or f?

and why does the program works backwards, for instance if I say f>m (which is true) it instead compares m to f rather than f to m.
and why does the program works backwards, for instance if I say f>m (which is true) it instead compares m to f rather than f to m.


The reason it doesn't return the expected result is because the logic in your implementation is wrong.
I would expect such a program to look more like the following: (Note the signature of operator>)

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

class box{

public:
    box(int a = 0, int b = 0, int c = 0) : h(a), l(b), w(c) {}

    double volume() const { return l*h*w; }

    bool operator > (const box& a) const { return volume() > a.volume(); }

    friend ostream& operator<<(ostream&os, const box& b);

private:
    double h;
    double l;
    double w;

};

ostream& operator<<(ostream& os, const box& b)
{
    return os << b.h << " x " << b.l << " x " << b.w;
}

int main(){

    //Question #2
    box x(1, 2, 3), g;
    box f(7, 8, 120), m(8, 6, 4);


    cout << "Comparing g (" << g << ") and x (" << x << ")\n";

    cout << " g (" << g.volume() << ") ";
    if (g > x)
        cout << "is greater ";
    else
        cout << "is not greater ";
    cout << "than x (" << x.volume() << ")\n";


    cout << "\nComparing m (" << m << ") and f (" << f << ")\n";

    cout << "m (" << m.volume() << ") ";
    if (m > f)
        cout << "is greater " ;
    else
        cout << "is not greater " ;
    cout << "than f (" << f.volume() << ")\n";
}


http://ideone.com/0noeAw

[edit: Note that the 'a' parameter in the operator> overload corresponds to the variable 'y' in the expression x > y]
Last edited on
Topic archived. No new replies allowed.