Thread: operator overloading

  1. #1
    Registered User Clayg's Avatar
    Join Date
    Nov 2011
    Location
    Hawaii
    Posts
    20

    operator overloading

    Okay. Operator overloading is now further mind F*&^^%^& me. I am now trying to fit it into the scheme of things. I know that yo declare it kind of like : object operator + (then another object here). Then somewhere else in my code I can write: object2+.(object4) and that adds the object 2 and 4 together. Is that right? Any one mind trying to dummify this for me? Preferably with a small example of actual delcaring and usage of the process... p-p-p-please:P
    I wonder how many years I will wander the streets of code until I realize where I am.

  2. #2
    Registered User
    Join Date
    Jun 2009
    Posts
    120
    Quote Originally Posted by Clayg View Post
    object2+.(object4) and that adds the object 2 and 4 together. Is that right?
    It depends on how you implement it. operator+ doesn't really has to add, it might also divide, print a message or do absolutely nothing.
    Example of very simple class:
    Code:
    class C1
    {
    private:
        int n;
    public:
        int operator+(const C1 &obj);
    };
    Now, let's define operator+ which actually adds member n of C1
    Code:
    int C1::operator+(const C1 &obj)
    {
        int addent1 = this->n;
        int addent2 = obj.n;
        int sum = addent1 + addent2;    
        cout << "Adding " << addent1 << " and " << addent2 << endl;
        cout << "Result: " << sum << endl;
        return sum;
    }
    And this one does totally something else
    Code:
    int C1::operator+(const C1 &obj)
    {
        this->n = -100000;
        cout << "Ha ha ha, I've changed n to " << this->n << endl;
        cout << "And result will always be 0 !" << endl;
        return 0;
    }

  3. #3
    Registered User Clayg's Avatar
    Join Date
    Nov 2011
    Location
    Hawaii
    Posts
    20
    okay, so you have made it public then showed the definition which to me resembles a function, yes? so when plugged into main what is it going to look like for either of the two defs you provided?
    main
    operator+ (&ofsomething);
    then the &ofsomething preforms the "overload"? or the function like aspect? taking the place of n in your examples?
    I wonder how many years I will wander the streets of code until I realize where I am.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Basically, overloading an operator means defining a function with a special name that takes a set number of arguments.

    So, if you overload operator+ as a member function, you declare it with one parameter (the right hand side parameter) since the left hand side parameter is the current object. You could call it with the usual member function call syntax:
    Code:
    a.operator+(b);
    but of course the reason for overloading operator+ in the first place is so you can make use of the syntactic sugar:
    Code:
    a + b;
    On the other hand, if you overload operator+ as a non-member function, you declare it with two parameters: the left hand side and right hand side, e.g.,
    Code:
    X operator+(const X& lhs, const X& rhs);
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User Clayg's Avatar
    Join Date
    Nov 2011
    Location
    Hawaii
    Posts
    20
    so based on the examples DRK gave the int main call of the overloaded operator would be, if usinf 3 in the passed argiment:
    3 + ;
    and, depending on example, the out come would be (if example number one): 3 + what ever is indide the definition?
    I wonder how many years I will wander the streets of code until I realize where I am.

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Sorry, I don't understand what you are trying to say.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    Here's an example with a main:
    Code:
    #include <iostream>
    
    class Int {
        int n_;
    public:
        Int(int n=0) : n_(n) { }
        int getN() const { return n_; }
    };
    
    Int operator+(const Int& a, const Int& b) {
        return Int(a.getN() + b.getN());
    }
    
    int main() {
        Int i(5), j(7);
        Int k = i + j;   // using operator+
        std::cout << k.getN() << "\n";
    }

  8. #8
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    The syntax for using any operator overload is exactly the same as the syntax for performing the operation directly on an int. Afterall, that's kind of the whole point.

    So if you know how to perform maths with an operator on an int e.g. int x = 42 / 7; then there is nothing you don't already know about the usage of the operator overloaded equivalent.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  9. #9
    Registered User Clayg's Avatar
    Join Date
    Nov 2011
    Location
    Hawaii
    Posts
    20
    Any one mind reviewing my attempt to overload operator+? Thank you in advance.
    Alright, here is my attempt at the operator overload of + and -. So far I have only called the + in main and have generated error codes:
    g++ -c -g -MMD -MP -MF build/Debug/Cygwin-Windows/4Cpoly1.o.d -o build/Debug/Cygwin-Windows/4Cpoly1.o 4Cpoly1.cpp
    4Cpoly1.cpp:34: error: `polynomial polynomial:perator+(const polynomial&, const polynomial&)' must take either zero or one argument
    4Cpoly1.cpp:40: error: `polynomial polynomial:perator-(const polynomial&, const polynomial&)' must take either zero or one argument
    4Cpoly1.cpp: In function `int main()':
    4Cpoly1.cpp:72: error: no match for 'operator+' in 'a + b'
    4Cpoly1.cpp:34: note: candidates are: polynomial polynomial:perator+(const polynomial&, const polynomial&)
    make[2]: Leaving directory `/cygdrive/c/Documents and Settings/Clay/Desktop/Programing/4Cpoly1'
    make[2]: *** [build/Debug/Cygwin-Windows/4Cpoly1.o] Error 1
    make[1]: *** [.build-conf] Error 2
    make[1]: Leaving directory `/cygdrive/c/Documents and Settings/Clay/Desktop/Programing/4Cpoly1'
    make: *** [.build-impl] Error 2
    BUILD FAILED (exit value 2, total time: 4s)


    Here is my code:


    Code:
    #include <cstdlib>
    #include <iomanip>
    #include <iostream>
    #include <math.h>
    using namespace std;
    /*
     * 
     */
    class polynomial
    {
    private:
        
        
    public:
        double first;
        
        polynomial(double x = 10);   //constructor with defaults
        ~polynomial();                      //destructor
        void setpolyx(double x);              //set x function
        
        double getpoly1() const;                          //get function for 1st poly
        
        
                    //below: + operator overload to add 2 polynomials
        polynomial polynomial::operator+(const polynomial &a, const polynomial &b)
            {
            return polynomial(( 2 * pow(a.getpoly1(),4)) + (2 * pow(b.getpoly1(), 4)));
            }
        
                    //below: - operator overload to subtract 2 polynomials
        polynomial operator-(const polynomial &a, const polynomial &b)
            {
            return polynomial(( 2 * pow(a.getpoly1(),4)) - (2 * pow(b.getpoly1(), 4)));
            }    
    };
    
    //definition of constructor 
    polynomial::polynomial(double x):
    first(x){}
            
    double polynomial::getpoly1() const        //definition of 1st get for 1st poly
    {
        return first;
    }
     
    void polynomial::setpolyx(double x)
    {
         first = x;                        //set first to x
        
    }
     
    int main() 
    {
        
    polynomial a(2);//a poly values initialized
    polynomial b(2);//b poly values initialized
    a.setpolyx(2);//a.first set to 5
    b.setpolyx(2);//b.first set to 6
    polynomial c(a + b) ;// polynomial c uses + overload to set c.first to 128
    cout << "2*"<<a.first <<"(4th) and 2*" << b.first<<"(4th)"<<endl;
    cout << "Are our two polynomials to work with."<< endl;
    cout <<"First the + operator overloaded" << c.first << endl;
        return 0;
    }
    I wonder how many years I will wander the streets of code until I realize where I am.

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Read my post #4 again on overloading as a member function versus overloading as a non-member function.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Registered User Clayg's Avatar
    Join Date
    Nov 2011
    Location
    Hawaii
    Posts
    20
    I love you Laserlight the C++ Witch.
    and I Like you dudes!!!
    wow, it worked that's pretty cool. It was such a simple thing I coudn't get me brain into it...
    Thank you to all of you.
    I wonder how many years I will wander the streets of code until I realize where I am.

  12. #12
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    In other words, you've given your + and - operators THREE parameters:
    1. a,
    2. b,
    3. *this
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  13. #13
    Registered User Clayg's Avatar
    Join Date
    Nov 2011
    Location
    Hawaii
    Posts
    20
    Nooooooooooooooo.... I don't get the *this yet. I will be asking about *this at another time and thread.
    I made them non-members and it works great with a tweak here and there. Thanks again!
    I wonder how many years I will wander the streets of code until I realize where I am.

  14. #14
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    What iMalc is trying to say is that when you put your operator + inside the class, the left-hand expression of the operator is the current object instance.
    Let me give you an example:
    Code:
    #include <iostream>
     
    class Int {
        int n_;
    public:
        Int(int n=0) : n_(n) { }
        int getN() const { return n_; }
    
        Int operator+(int b) {
            return Int(getN() + b);
        }
    };
    
    int main() {
        Int i(5);
        int j = 7;
        Int k = i + j;   // using operator+
        std::cout << k.getN() << "\n";
    }
    The operator "+" has two operands: to the left of it (the left-hand side expression, which I will call "lhs"), and to the right of it (the right hand expression which I will call "rhs").
    In you put the operator inside the class, the lhs will always be an instance of that class (in this example, Int).
    If you put it outside the class, then you must tell the compiler what type the lhs is.

    The above code should compile, but throw the order of the expressions around, as in the following example, and it will compile no longer:
    Code:
    #include <iostream>
     
    class Int {
        int n_;
    public:
        Int(int n=0) : n_(n) { }
        int getN() const { return n_; }
    
        Int operator+(int b) {
            return Int(getN() + b);
        }
    };
    
    int main() {
        Int i(5);
        int j = 7;
        Int k = j + i;   // using operator+
        std::cout << k.getN() << "\n";
    }
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  15. #15
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    One last thing is that it is preferable to make some operator overloads non-members and to make some members.
    Operators that modify an item's value should generally be member functions and those that don't should generally not be. Those that only take one argument such as --, !, or unary minus, can go either way IMHO.
    Member: -=, +=, *=, /=, =
    Non-member: +, -, *, /, ^, |, &, <, >, <=, >=, ==, !=
    The choice you've made is a good one in this regard.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Overloading operator ==
    By anon in forum C++ Programming
    Replies: 4
    Last Post: 05-10-2006, 03:26 PM
  2. Operator Overloading
    By kennny2004 in forum C++ Programming
    Replies: 2
    Last Post: 05-04-2006, 11:07 PM
  3. Operator overloading.......
    By aldajlo in forum C++ Programming
    Replies: 7
    Last Post: 10-19-2004, 01:47 PM
  4. Overloading -> operator
    By Hunter2 in forum C++ Programming
    Replies: 0
    Last Post: 05-10-2004, 03:08 PM
  5. operator overloading
    By tsut in forum C++ Programming
    Replies: 1
    Last Post: 03-29-2002, 09:26 AM