I'm trying to create some classes that work together via Operator Overloading. I have the main.cpp and the Distance.h files exactly how I want them, and now I just need help properly setting up my Distance.cpp file to link properly and run accurately with them. Here's a look at what I've got so far. Any help and tips would be GREATLY appreciated. Again, the main.cpp and the Distance.h (header file) do not (CANNOT) be changed, so the focus is on the Distance.cpp file. Thanks in advance for any help!!

// ************************************************
// Distance.h
// ************************************************
#include <iostream>
using namespace std;


class Distance                    //English Distance class
{
private:
    int feet;
    int inches;

    // Normalize adjusts feet and inches if inches is >= 12;
    void Normalize();

    // utility function to return Distance in inches
    int sizeInInches();
    
public:
    
    // Constructors
    Distance();  // default constructor setting feet=0 and inches=0
    Distance(int initialValueInInches);

    // used for int x = dist1;
    operator int();
    
    // used for dist1 = dist1 + dist2;
    Distance operator + (Distance & d2) const;
	//EXAMP: Distance operator + (Distance) const;

    // used for dist1 += dist2;
    void operator += (Distance & d2);

    // used for dist1 += 22;
    void operator += (int value);

    // used for dist1 = dist2
    void operator = (Distance & d2);

    // used for dist1 = 22
    void operator = (int value);

    // used for if (dist1 == dist2) ...
    bool operator == (Distance & d2)  ;

    // used for if (dist1 < dist2) ...
    bool operator < (Distance & d2) ;

    
    // **************************************

    void getdist()              //get length from user
    {
        cout << "\n   Enter feet: ";  cin >> feet;
        cout << "   Enter inches: ";  cin >> inches;
    } 
    void showdist()
    {
        cout << " feet=" << feet << " inches=" << inches;
    }
};

class ArrDistance
{
    Distance * arr;
    int arrSize;
public:
    // Constructor creates an Array of Distance classes the 
    // size specified in size.  
    ArrDistance(int size);

    // Make sure you free up your dynamic allocation
    ~ArrDistance();


    // This operator should do a sanity check on the index
    Distance & operator [](int index);
};






// *************************************************
// Main.cpp
// *************************************************
#include <iostream>
using namespace std;
#include "Distance.h"



int main()
{
  Distance d1(20), d2(17), d3;

  d3 = d1 + d2;

  cout << "d1="; d1.showdist();  cout << endl;
  cout << "d2="; d2.showdist();  cout << endl;
  cout << "d3="; d3.showdist();  cout << endl;

  Distance d4(13);
  d3 += d4;
  cout << "d3="; d3.showdist(); cout << endl;

  d3 += 22;
  cout << "d3="; d3.showdist(); cout << endl;

  d3 = d4;
  cout << "d3="; d3.showdist(); cout << endl;

  d3 = 22;
  cout << "d3="; d3.showdist(); cout << endl;
  

  ArrDistance darr(10);
  for (int i=0; i <= 10; i++)
  {
      darr[i] = 13 +i;
      cout << "darr["<<i<<"]="; darr[i].showdist(); cout << endl;
      if (d2 == darr[i]) 
          cout << " Equal to d2 " << endl;
      
      if (darr[i] < d2) 
          cout << " Less than d2 " << endl;
  }

   return 0;
}









// *************************************************
// Distance.cpp
// *************************************************

#include <iostream>
using namespace std;
#include "Distance.h"



// Normalize adjusts feet and inches if inches is >= 12;
void Distance::Normalize()
{
	if(inches >= 12)
	{
		inches -= 12;
		feet++;
	} 
}

// utility function to return Distance in inches
int Distance::sizeInInches()
{
	inches = feet/12;
	return inches;
}

    
Distance::Distance() : feet(0), inches(0)
{} 



Distance::Distance(int initialValueInInches)
{
	inches = initialValueInInches;
	feet = 0;
	Normalize();
}


// used for int x = dist1;
Distance::operator int()
{
     //???
	return 0;
}
    

// used for dist1 = dist1 + dist2;
Distance Distance::operator + (Distance & d2) const
{
	feet += d2.feet;                    //add the feet
        inches += d2.inches             //add the inches
	if(inches >= 12)                   //if total exceeds 12.0,
	{                                        //then decrease inches
		d2.inches -= 12;                  //by 12.0 and
		d2.feet++;                        //increase feet by 1
	}                                        //return a temporary Distance
	return Distance(d2); 
}


// used for dist1 += dist2;
void Distance::operator += (Distance & d2)
{
	feet += d2.feet;
	inches += d2.inches;
	Normalize();  
}


// used for dist1 += 22;
void Distance::operator += (int value)
{
	
}



// used for dist1 = dist2
void Distance::operator = (Distance & d2)
{}


// used for dist1 = 22
void Distance::operator = (int value)
{}


// used for if (dist1 == dist2) ...
bool Distance::operator == (Distance & d2)
{
	int b1 = feet + inches/12;
	int b2 = d2.feet + d2.inches/12;
	return (b1 == b2) ? true : false;
}



// used for if (dist1 < dist2) ...
bool Distance::operator < (Distance & d2)
{
	int b1 = feet + inches/12;
	int b2 = d2.feet + d2.inches/12;
	return (b1 < b2) ? true : false;
}


    // Constructor creates an Array of Distance classes the 
    // size specified in size.  
ArrDistance::ArrDistance(int size)
{
	arrSize = size;
	arr = new Distance[arrSize];
}


    // Make sure you free up your dynamic allocation
ArrDistance::~ArrDistance()
{
	delete [] arr;
}




    // This operator should do a sanity check on the index
Distance & ArrDistance::operator [](int index)
{
	if(index < 0 || index >= arrSize)
	{
		cout << "\nIndex out of bounds";
		exit(1);
	}
	return arr[index];
}

As you can see, I haven't filled in all the operator void functions yet, but thats also part of my struggle. Let me know what you guys think!!

Recommended Answers

All 11 Replies

The int() operator should return sizeInInches(). Also, watch it, your sizeInInches() function is not correct: you return the number of feet in inches but forget any extra inches there may have been in inches before calling the function. Since you don't want to normalize or un-normalize, use a local variable instead of modifying inches.

Your += operator is perfect. However, your + operator is not. Assume: d1 = [b]d2[/b] + d3 (not what you've got written above the function definition). Never modify the objects on either side of the + operator. The user wants a new object (d1). Hint: make a new return value as a copy of d2, then add d3 to it, and then return it.

When doing '+= int' think again what the int stands for: number of inches. Just add the int value to the inches and normalize.

In your comparison operators (== and <), be careful. You want to compare the sizeInInches(). (Also, be careful what it is you divide by 12 --moot point.) Finally, return (x < z) ? true : false; is a bit wordy. The expression x < z itself returns a boolean value, so you really only need to say: return (x < z); That should be enough to get you right. Good luck.

Ok maybe I'm just dumb or something, but this language just boggles my mind soo much! I understand everything you're saying, I just can't convert it to C++ language to make it work with the code I have.

I don't know if you can dumb it down for me somehow or something maybe!? Thanks.

For example, when you say:

'forget any extra inches there may have been in inches before calling the function'

, what do I need to code to fix/accomodate for that!?
Similarly, when you say to just use a local variable instead of modifying inches I'm not sure how to go about that either. Is it just a matter of:

int fe;
fe /= 12;
return fe;

That doesn't seem right either. I'm not understanding when it is being called and what I need to put in there to use it. That's my problem with pretty much everything. I don't understand when the functions are being called and how they're being used, so I'm not sure what to place in their bodies to make them do those things. Sorry, I'm not to quick with any of this, but hopefully you'll have the grace and patience to help me through...?!

[EDIT] Balla4eva33 posted the last message as I was posting this one, so this should be read as post #4 and balla's post #4 as post #5.[/EDIT]

Don't feel stupid. You are just going through what we all do (or did) when learning this stuff. Just keep thinking about it, and reading about it, and trying stuff. Eventually you'll "get" it.

I've already given you a pretty "dumbed down" answer (yeah... don't feel bad). Try to think it through for a day or so and if you are still completely lost post again and I'll help more. Even if your new tries don't work, post them.

Makes your brain feels like a walnut in a nutcracker, no?

Oh yeah, here's a good hint: don't write the same code over and over again. Notice how the sizeInInches() method (i.e. class function) is private. That means it is only meant to be used by methods of your class, such as the int() operator function and your comparison operators and etc. It is perfectly OK to use it over and over again.

Think about it and post again.:cool:

OK. Your class stores two pieces of information: feet and inches.
Every foot is 12 inches, so if a distance is 70 inches you can't just store it as feet without rounding it up or down to the nearest foot. If you look at normalize() you'll see that you take those 70 inches, get the 70/12=5 feet out of it and store that in feet, and store the remaining 10 inches in inches.

Likewise, the sizeInInches() works in reverse. The return value is the total number of inches, which is ((feet * 12) + inches), right? By using a local variable you are correct. Create a new int inside your function, do the proper calculations to give it a value, and return it.

int result;  // create a local variable (one we'll forget when the function is done)
result = feet * 12;  // convert feet to inches
result += inches;  // add any remaining inches
return result;  // return the total inches

Notice how I used the mathematical formula exactly?

Making things work is just a matter of not giving up. Eventually you'll make sense of it.

Good luck.

Ok, thanks for the help you've provided thus far. I'll attack it some more and then I'm sure I'll be back later! :)

Regarding my operator + function, how else can I write this to make it work for me? I think I sorta got the idea down, but it's not working because I don't have a Distance function that takes two parameters.

{
        int f = feet + d2.feet;
	int i = inches + d2.inches;
	if(i >= 12)
	{
		i -= 12;
		f++;
	}
	return Distance(f,i);
}

Actually, you have done a very good job.

When you say: d1 = d2 + d3; you are actually doing two operations: d2 + d3 and then d1 = dtemp When you overload operators in-class as you are (that is, where the operator functions themselves are actually class methods instead of friend functions) what happens is that the left-hand operand's operator function is called with the right hand operand as the argument value. Hence: d2 + d3 is really the same thing as: d2.operator+( d3 ) When adding two things, you want to return a new value without modifying either of the addends, which is why I had you change it.


Now, what I'd like you to notice is that you had to repeat yourself to avoid modifying d2: you created two ints and did the same thing that normalize() does, and only then created a new Distance object as the return value.

Why not first create the new Distance object (instead of two ints), set it equal to d2, then add d3 to it with a function you already have, then return the new distance object?

Does that make sense?

Hmm, okay, I see what you're saying.

Now, for the function, what if I do it like this instead? I think this works...

Distance d3;
	int f = feet + d2.feet;
	int i = inches + d2.inches;
	if(i >= 12)
	{
		i -= 12;
		f++;
	}
	d3.feet = f;
	d3.inches = i;
	return d3;

And I believe these are the correct comparison operator functions now?!?:

bool Distance::operator == (Distance & d2)
{
	int b1 = inches + feet*12;
	int b2 = d2.inches + d2.feet*12;
	if  (b1 == b2)
		return true;
	else
		return false;
}




bool Distance::operator < (Distance & d2)
{
	int b1 = feet*12 + inches;
	int b2 = d2.feet*12 + d2.inches;
	if  (b1 < b2)
		return true;
	else
		return false;
}

I think that solves it all. It seems to compile as needed now! Thank you soo much for your help. Do you see any errors still on the final...:

MAIN.CPP:

#include <iostream>
using namespace std;
#include "Distance.h"



void Distance::Normalize()
{
	if (inches >= 12)
	{
		do
		{
			inches -= 12;
			feet++;
		}
		while (inches >= 12);
	}
}


int Distance::sizeInInches()
{
	int result;
	result = feet * 12;
	result += inches;
	return result;
}

    
Distance::Distance() : feet(0), inches(0)
{} 



Distance::Distance(int initialValueInInches)
{
	inches = initialValueInInches;
	feet = 0;
	Normalize();
}



Distance::operator int()
{
	return sizeInInches();
}
    


Distance Distance::operator + (Distance & d2) const
{
	Distance d3;
	int f = feet + d2.feet;
	int i = inches + d2.inches;
	if(i >= 12)
	{
		i -= 12;
		f++;
	}
	d3.feet = f;
	d3.inches = i;
	return d3;
}



void Distance::operator += (Distance & d2)
{
	feet += d2.feet;
	inches += d2.inches;
	Normalize();
}



void Distance::operator += (int value)
{
	inches += value;
	Normalize();
}



void Distance::operator = (Distance & d2)
{
	feet = d2.feet;
	inches = d2.inches;
	Normalize();
}



void Distance::operator = (int value)
{
	feet = 0;
	inches = 0;
	inches = value;
	Normalize();
}



bool Distance::operator == (Distance & d2)
{
	int b1 = inches + feet*12;
	int b2 = d2.inches + d2.feet*12;
	if  (b1 == b2)
		return true;
	else
		return false;
}




bool Distance::operator < (Distance & d2)
{
	int b1 = feet*12 + inches;
	int b2 = d2.feet*12 + d2.inches;
	if  (b1 < b2)
		return true;
	else
		return false;
}



 
ArrDistance::ArrDistance(int size)
{
	arrSize = size;
	arr = new Distance[arrSize];
}



ArrDistance::~ArrDistance()
{
	delete [] arr;
}



Distance & ArrDistance::operator [](int index)
{
	if(index < 0 || index >= arrSize)
	{
		cout << "\narray reference out of bounds: " << index;
		cout << "\nReturning first array entry\n";
	}
	return arr[index];
}

Very good. Just a few thoughts:

In your functions, you keep doing stuff you already have functions for. In the new operator+ method, you create the Distance object first, but you still don't use it until you are ready to return a value. Hint, use: Distance d3( sizeInInches() ); Now use an overloaded operator method you have elsewhere to add d2 to d3. No need to play with the feet and inches, or normalize them, because the other functions you already have will do all that for you. Make sense?

Likewise, in your comparison methods (operator== and operator<) there is no need to find the total number of inches yourself. You already have the sizeInInches() function to do that for you. Also, there is no need to say if (x < y) return true; else return false; The < operator returns a boolean value, so just use it directly: return (x < y); Good luck.

Great, thanks again. I got it all now, and I'm VERY grateful for your help! I'm sure I'll be back again with new problems!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.