Thread: About operator overloading...

  1. #1
    Registered User
    Join Date
    Apr 2003
    Posts
    17

    Question About operator overloading...

    I'm rather new to C++ and I couldn't find an answer in the FAQ- I was reading some less-than-lucid text recently about operator overloading, and I didn't understand a.) what it is or what it's for or b.) how you implement it on the most basic level. Could anybody be so kind as to clarify the situation for me? Thanks all.
    "None are more hopelessly enslaved than those who falsely believe they are free."
    -Goethe

    [paraphrased] "Those who would sacrifice essential liberties for a little temporary safety deserve neither."
    -Benjamin Franklin

  2. #2
    Funniest man in this seat minesweeper's Avatar
    Join Date
    Mar 2002
    Posts
    798
    Operator overloading allows you to extend the functionality of the operators. For example if you do:

    Code:
    int a = 5;
    cout << a;
    It will print out '5';

    But if you do

    Code:
    int a [] = {1, 2, 3};
    cout << a;
    expecting it to print out your three numbers, you will be disappointed as it won't work like that. Now we can overload the stream operator '<<' to accept an array and print out the elements for you as follows:

    Code:
    #include <iostream.h>
    #include <stdlib.h>
    
    #define ELEMENTS 3
    void operator << (ostream &out, int a[])
    {
    
          for ( int i = 0; i < ELEMENTS; i++)
         {
                out << a[i] << " ";
         }
    
    }
    
    int main()
    {
    
          int x[] = {1, 2, 3};
          cout << x;
          
          return 0;
    }
    Is that any clearer?

  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Operator overloading in usually employed in the context of classes. Lets say you declare a class called Cat like this:
    Code:
    class Cat
    {
    public:
    	Cat(string its_color, double its_weight)
    	{
    		color = its_color;
    		weight = its_weight;
    	}		
    private:
    	string color;
    	double weight;
    };
    If you declare two cat objects, cat_1 and cat_2, you have to decide what you want cat_1 + cat_2 to mean, as well as what you want something like cat_1 + 3 to mean. When you define what you want the + operator to do to your objects that's called operator overloading.

    If your new to C++, and haven't coded some programs with classes yet, you have a lot to learn before you need to ever worry about operator overloading. You need to study functions, pointers, and references, and the basics of classes like constructors and destructors first.
    Last edited by 7stud; 04-12-2003 at 12:47 PM.

  4. #4
    Registered User
    Join Date
    Apr 2003
    Posts
    17

    Smile

    Woah, thanks! haha That's a lot of code!

Popular pages Recent additions subscribe to a feed