Overloading the '>' operator

I overloaded the '>' operator to compare the volumes of two objects that are cones. I seem to be having a problem when I compare the values of maxCone with the cones in the array.
I first null the pointer and begin to compare the values which should be comparing just the volumes since I overloaded it that way, right?

Now, when I run the program it will compare but it will not always give me the largest volume. I've found that if I have a small, large, then a smaller value in my array it will go through it sequentially and it will assign maxCone to the smaller value.

(EX: 3,5,4. My pointer maxCone would output 4 as the max volume after comparing them all.)

I can't find my mistake.
I would appreciate any help.

1
2
3
4
	bool Cone::operator>(const Cone& obj) const
	{
		return this->getVolume() > obj.getVolume();
	}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 void MaxVolumeCone(FArrayList<Cone*>& cones)
{
	Cone* maxCone;
	int i;
	if(cones.getCount() == 0)
	{
		cout << endl << "List is Empty!" << endl;
	}
	else
	{
		for(i = 0; i < cones.getCount(); i++)
		{

			if(cones[i] > maxCone)
			{
				maxCone = cones[i];	
			}
		}
Last edited on
The pointer maxCone is declared at line 3, but not initialised. It contains some garbage value.
I set it equal to zero but the problem persists. :(
What's more both maxCone and cones[i] are pointers to Cone.

Since they are not Cone, but pointers to Cone, your overloaded operator> will not be used.
Pointers are compared with the "regular" built-in operator>.

First, make maxCone a Cone. Then dereference cones[i]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 void MaxVolumeCone(FArrayList<Cone*>& cones)
{
	Cone maxCone;
	int i;
	if(cones.getCount() == 0)
	{
		cout << endl << "List is Empty!" << endl;
	}
	else
	{
		for(i = 0; i < cones.getCount(); i++)
		{

			if(*cones[i] > maxCone)
			{
				maxCone = *cones[i];	
			}
		}


Edit: small mistake.
Last edited on
I had to use the dereference operator on both sides. I believe the reason for this was as you said in your previous post. It appears that error is gone. Thank you for your help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void MaxVolumeCone(FArrayList<Cone*>& cones)
{
	Cone* maxCone = cones[0];
	int i;
	if(cones.getCount() == 0)
	{
		cout << endl << "List is Empty!" << endl;
	}
	else
	{
		for(i = 1; i < cones.getCount(); i++)
		{

			if(*cones[i] > *maxCone)
			{
				*maxCone = *cones[i];	
			}
		}
Topic archived. No new replies allowed.