Adding a set of class objects to a master class object

advertisements

for a project I had to create a class that had variables for feet and inches, and had a method to add these variables together from object 1 and object 2, then object 3, 4, and so on.

CDistance CDistance::add(const CDistance& yourDist) const
{
    CDistance total;
    total.feet += yourDist.feet;
    total.inches += yourDist.inches;
    /*if (total.inches > 12)
    {
        total.feet += (total.inches / 12);
        total.inches = total.inches % 12;
    }*/
    return total;
}

that's the method I have for adding, and here is a function in the main source file, where I process each class

void printAndAdd(const CDistance distList[], int size)
{
    CDistance new_total;
    new_total = distList[0].add(distList[1].add(distList[2].add(distList[3].add(distList[4]))));
    new_total.printDist();
}

And here is the method I use to print out the data on screen

void CDistance::printDist() const
{
    cout << "Feet: " << this->feet << "\n\n";
    cout << "Inches: " << this->inches << "\n\n";
}

I thought about using a for loop, for that 2nd line, but I'm having a bit of a problem. Whenever I print the data out, it's 0. As if the add function isn't working, which I'm not quite sure I even understand what I did. From what I think I'm doing, it's creating a new obejct, adding the variables from the referenced to object to the created object, that commented out section is a section I just took out for now and will add later, and then it returns the object. When I call the function in my main source file it would set the object new_total equal to the sum of object 0, 1, 2, 3, and 4. Am I close, or way off to what's actually happening? I should also explain that I've only been programming for about a year, it's really intriguing to me, but naturally difficult at times, and I'm still trying to grasp my hands around the idea of classes in c++.


The problem is that you never use the instance variables when adding. Instead you always start from a freshly minted object. Try this:

CDistance CDistance::add(const CDistance& yourDist) const
{
    CDistance total(*this);
    total.feet += yourDist.feet;
    total.inches += yourDist.inches;

    this->feet += yourDist.feet;
    this->inches += yourDist.inches;
    return total;
}