Problems with an addition operator

This is a discussion on Problems with an addition operator within the C++ Programming forums, part of the General Programming Boards category; I am wondering if anyone can help me, I fairly new to C++ and am trying to implement an addition ...

  1. #1
    Registered User
    Join Date
    Aug 2002
    Posts
    14

    Problems with an addition operator

    I am wondering if anyone can help me, I fairly new to C++ and am trying to implement an addition operator that acceptsan object based on another class as a parameter. I have tried a few things, but I fear I am way off base. My code worked up until the point of implementing the addition operator.

    If anyone could help or give me a push in the right direction I would really appreciate it!

    <code>

    //first class

    #include <iostream>
    using namespace std;

    class Course
    {
    public:
    Course(string nameValue, int yearValue);

    Course(int yearValue);

    Course();

    //my not working addition operator
    const Course operator +(const Course& vEnrol, const Course& vcost);

    void output();

    private:
    int vCost;
    int vEnrol;
    int year;
    string name;
    };


    //my second class

    #include <iostream>
    using namespace std;

    class Enrolment
    {

    public:
    Enrolment(int enrolValue, int costValue);

    private:
    int cost;
    int enrol;
    };


    //main

    #include <iostream>
    #include <string>
    #include "Course.h"
    #include "Enrolment.h"

    using namespace std;



    int main(int argc, char* argv[])
    {

    Course a("English", 2003);
    Course b("Maths", 2003);

    // initialising the Enrolment constructor
    Enrolment(0,0);

    cout<< "Before Enrolments:" << endl;

    a.output();
    b.output();

    //This part does not work
    a = a + Enrolment(50, 500);
    a = a + Enrolment(20, 200);

    cout<< "After Enrolment:" << endl;
    cout<< "=================" << endl;
    a.output();
    b.output();

    return(0);
    }


    Course::Course(string name_, int year_)
    : class(name_), year(year_)
    {
    }


    Enrolment::Enrolment(int enrol_, int cost_)
    : enrol(enrol_), cost(cost_)
    {
    }



    //test addition operator

    const Course operator +(const Course& vEnrol, const Course& vcost)
    {
    int vEnrol = vEnrol + Enrolment.enrol;
    int vcost = vcost + Enrolment.cost;

    return Enrolment(venrol, vcost);
    }

    void Course:utput()
    {

    cout<<"Course: "<<name<<" "<<year<< endl;
    cout<< "Total enrolement :" <<venrol<<endl;
    cout<<"Total Income : "<<vcost<<endl;
    cout<<endl;

    }
    </code>

  2. #2
    ¡Amo fútbol!
    Join Date
    Dec 2001
    Posts
    2,136
    Your addition operator isn't overloaded for Enrollment.

  3. #3
    Registered User
    Join Date
    Aug 2002
    Posts
    14
    I am not sure how to do that (overload my operator for enrolments from within the Course class). I tried a few different things, but it is becoming increasingly obvious that I haven't got a clue.

    I used :

    const Course operator +(const Course& vEnrol, const Course& vcost);

    but do not know the correct syntax for calling another class as an object.

  4. #4
    Senior Member joshdick's Avatar
    Join Date
    Nov 2002
    Location
    Phildelphia, PA
    Posts
    1,146
    A little point on your design: I think adding two courses together would yield a schedule, not another course. What is the desired result of your addition?
    FAQ

    "The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs." -- Joseph Weizenbaum.

    "If you cannot grok the overall structure of a program while taking a shower, you are not ready to code it." -- Richard Pattis.

  5. #5
    Registered User
    Join Date
    Aug 2002
    Posts
    14
    Hi joshdick, the desired output of


    a = a + Enrolment(50, 500);
    a = a + Enrolment(20, 200);

    should be:
    course enrol: 70
    cost 700.

    (which should show in the output function.). It is not the most obvious way of doing it, but it is the way it was set to me by my school. I guess it is trying to teach us certain ways of doing things, only I am still trying to learn what it is!

    Cheers.

  6. #6
    Registered User
    Join Date
    Mar 2003
    Posts
    1
    hey i need a solution for that too. . Does anoyone know how to do the implementation? like how do u add up 50 and 20, 500 and 200? I know you have to do it with operator overloading but when i put
    //Header File
    const operator +(const Enrolment& enrol);

    //Source File
    Student Student:perator +(const Enrolemtn& enrol)
    {
    }

    it gives me a syntax error
    a = a + Enrolment(50, 500);
    a = a + Enrolment(20, 200);

  7. #7
    The Pantless Man CheesyMoo's Avatar
    Join Date
    Jan 2003
    Posts
    262
    Correct me if I'm wrong but I don't think you can start a function with a return type of const.
    If you ever need a hug, just ask.

  8. #8
    Registered User
    Join Date
    Mar 2003
    Posts
    13
    hm....I have the same kind of problem on operator overloading.

  9. #9
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    Code:
    #include <iostream>
    
    using namespace std;
    
    struct Sample
    {
        int first;
        int second;
        void operator +(const Sample &);
        friend const Sample & operator +(const Sample &,  const Sample&);
    };
    
    void  Sample::operator+(const Sample & s)
    {
       first += s.first;
       second += s.second;
    }
    
    const Sample & operator+(const Sample & rhs, const Sample & lhs)
    {
      Sample result;
      result.first = rhs.first + lhs.first;
      result.second = rhs.second + lhs.second;
      return result;
    }
    
    int main()
    {
      Sample my;
      Sample yours;
      Sample ours;
    
       my.first = 20;
       my.second = 500;
    
       yours.first = 50;
       yours.second = 500;
    
       cout << "my.first = " << my.first << " and my.second = " << my.second;
    
       cout << "yours.first = " << yours.first  << " and yours.second = " << your.second << endl;
       
       //using the + operator overloaded as a friend function
       ours = my + yours;
    
       cout << "ours.first = " << ours.first << " and ours.second = " << ours.second << endl;
       
       //using the + operator overloaded a struct method
       my + yours;
      
       cout << "my.first = " << my.first << " and my.second  = " << my.second << endl;
       
       return 0;
    }
    I haven't compiled and/run the obove code, so all bets are off in terms of errors, etc., but they should be minor, if any.

    The code implements a crude struct (so I don't have to monkey with access details) that has two int members and overloads the + operator two different ways. The first + operator is a class method that takes a single object as input and adds it to the object calling the + operator, effectively changing the values of the calling objects data members. The second + operator is a friend function with public access. That means it is not a member of the struct, but may use the structs data members, even if I had declared them as private. Note that the friend + operator needs two objects as input and returns a third object which is then assigned to fourth object. I then declare several instances of the struct, and initialize two of them. I display the original values. Then I call the two + operators to demonstrate their use, and display the results.

    HTH.
    Last edited by elad; 03-27-2003 at 11:58 AM.

  10. #10
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    sorry elad its not good. You return void from your addition operators member.

    You want in an addition

    A= B+C

    for A to be a new value and for B and C to be constant.
    Does your operator + do that?

    The other 1 as a nonmember is worse.
    You return a reference. This is bad operator + should return an object. What do u return a reference to? Its a local variable that has been destroyed.

    Thats 2 large cock-ups in 1 small example. Back to the drawing board!
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  11. #11
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    I'm not sure I would call them cock ups, let alone large, but I do appreciate constructive criticism. Posting answers frequently helps me as much as anyone else. Therefore, I will attempt to correct the shortfalls in my previous code as pointed out by Stoned-Coder.

    Code:
    #include <iostream>
    
    using namespace std;
    
    struct Sample
    {
        int first;
        int second;
        void operator +=(const Sample &);
        Sample operator+(const Sample &);
        friend Sample operator +(const Sample &,  const Sample&);
    };
    
    void  Sample::operator+=(const Sample & s)
    {
       first += s.first;
       second += s.second;
    }
    
    Sample Sample::operator+(const Sample & s)
    {
       Sample result;
       result.first = first + s.first;
       result.second = second + s.second;
       return result;
    }
    
    Sample operator+(const Sample & rhs, const Sample & lhs)
    {
      Sample result;
      result.first = rhs.first + lhs.first;
      result.second = rhs.second + lhs.second;
      return result;
    }
    
     
    int main()
    {
      Sample my;
      Sample yours;
      Sample ours;
    
       my.first = 20;
       my.second = 500;
    
       yours.first = 50;
       yours.second = 500;
    
       cout << "my.first = " << my.first << " and my.second = " << my.second;
    
       cout << "yours.first = " << yours.first  << " and yours.second = " << your.second << endl;
       
       //using the + operator overloaded as a friend function
       ours = my + yours;
    
       cout << "ours.first = " << ours.first << " and ours.second = " << ours.second << endl;
       
       //using the += operator overloaded a struct method
       my += yours;
      
       cout << "my.first = " << my.first << " and my.second  = " << my.second << endl;
    
       //using the + operator overloaded as a struct method and the new values of my resulting from above
    
       ours = my + yours;
    
       cout << "ours.first = " << ours.first << " and ours.second = " << ours.second << endl;
       
       return 0;
    }
    And, again, without having the opportunity to test this by compiling/running, or by reviewing my code with my reference text, I won't gaurantee it's free of mistakes, but I think I have corrected those pointed out by Stoned-Coder. The basic plan remained the same, with minor modifcations.

    Now that I think about this program, it might have a bug in it, in that the compiler might not know whether to call the + operator overloaded as the friend function or the struct method when it finds the lines:

    ours = my + yours;

    Therefore it may say "ambiguous function call" or something to that effect. So, I guess in any given program I would use one style or the other, but not both.
    Last edited by elad; 03-27-2003 at 03:48 PM.

  12. #12
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    better but still not quite there. There is a way on most current compilers to get rid of that temporary and make this efficient. Its such an important optimization that it has been given a name. Its called the return value optimization.
    Code:
    // Yours...
    Sample operator+(const Sample & rhs, const Sample & lhs)
    {
      Sample result;
      result.first = rhs.first + lhs.first;
      result.second = rhs.second + lhs.second;
      return result;
    }
    
    // now mine...
    const Sample operator +(const Sample& lhs, const Sample& rhs)
    {
       return Sample( (lhs.first+rhs.first),(lhs.second+rhs.second));
    }
    This assumes that you have a Sample(int,int) constructor but with a class like that one that constructor would make perfect sense and makes writing operator + a doddle.Notice how in your func you have a named object. Named objects cannot be eliminated even if they are not used. My func suffers from no such problem so is efficient as long as the compiler supports the RVO otherwise it offers little over yours.

    edit...
    Also you should return a reference to the current object in operator +=.This will allow cascading.
    Last edited by Stoned_Coder; 03-27-2003 at 08:10 PM.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  13. #13
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    Thank you for your input. It is appreciated.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. operator problems
    By hdragon in forum C++ Programming
    Replies: 10
    Last Post: 12-30-2005, 11:47 PM
  2. C++ Operator Overloading help
    By Bartosz in forum C++ Programming
    Replies: 2
    Last Post: 08-17-2005, 01:55 PM
  3. overloading operator problems
    By almich in forum C++ Programming
    Replies: 2
    Last Post: 07-26-2004, 05:10 PM
  4. evaluating unary negation operator in an infix expression??
    By YevGenius in forum C++ Programming
    Replies: 7
    Last Post: 05-12-2004, 02:18 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21