Thread: Overloading

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    9

    Overloading

    I am trying to understand overloading. I don't think I quite get why you would need to overload an operator or function. Can anyone help clear this up for me?

    Thank you

  2. #2
    S­énior Member
    Join Date
    Jan 2002
    Posts
    982
    It's not really neccessary to use overloading, but it can make your code easier to read and keep consistent. Look at the following example -

    Code:
    #include <iostream>
    
    using std::cout;
    using std::endl;
    using std::ostream;
    
    class MyInt
    {
    private:
    	int theInt;
    public:
    	MyInt(int b):theInt(b){}
    
    	MyInt operator+(MyInt &b)const{
    		return MyInt(theInt+b.Get());
    	}
    
    	int add(MyInt b)const{
    		return theInt+b.Get();
    	}
    	
    	void Print()const{
    		cout << theInt;
    	}
    
    	void Set(int b){
    		theInt=b;
    	}
    
    	int Get()const{
    		return theInt;
    	}
    	
    	friend ostream& operator<<(ostream& os,MyInt i){
    		return os << i.theInt;
    	}
    
    };
    
    
    
    
    int main(){
    
    	//With operator overloading
    	MyInt a=10;
    	MyInt b=20;
    	MyInt c=30;
    
    	MyInt d = a+b+c;
    
    	cout << a << "+" << b << "+" << c << "=" << d << "\n";
    
    	//Without operator overloading
    	a.Set(10);
    	b.Set(20);
    	c.Set(30);
    
    	d.Set(a.Get()+b.Get()+c.Get());
    
    	a.Print();
    	cout.put('+');
    	b.Print();
    	cout.put('+');
    	c.Print();
    	cout.put('=');
    	d.Print();
    	cout.put('\n');
    
    	return 0;
    }

    Which one is easier to understand doing a quick scan of the code?

  3. #3
    Registered User
    Join Date
    Sep 2001
    Posts
    9

    thank you

    Thank you so much! I'm going to read over this tonight.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Overloading operators
    By ugmusicbiz in forum C++ Programming
    Replies: 2
    Last Post: 02-13-2009, 01:41 PM
  2. unary operator overloading and classes
    By coletek in forum C++ Programming
    Replies: 9
    Last Post: 01-10-2009, 02:14 AM
  3. Overloading operator ==
    By anon in forum C++ Programming
    Replies: 4
    Last Post: 05-10-2006, 03:26 PM
  4. operator overloading
    By blue_gene in forum C++ Programming
    Replies: 6
    Last Post: 04-29-2004, 04:06 PM
  5. overloading
    By theLukerBoy in forum C++ Programming
    Replies: 6
    Last Post: 11-04-2002, 08:49 PM