C++
  Home arrow C++ arrow Page 3 - Operator Overloading in C++
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C++

Operator Overloading in C++
By: Ben Watson
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 253
    2002-12-08

    Table of Contents:
  • Operator Overloading in C++
  • Definition
  • Overloading =
  • Overloading
  • Matrix Multiplication - Overloading * Again
  • Putting It All Together
  • Conclusion

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Operator Overloading in C++ - Overloading =


    (Page 3 of 7 )

    The only other operator we need to overload is assignment (=). When overloading assignment, we must keep in mind that the object we're assigning to must already exist, and it is that object's operator= method which will be called.

    Row& operator=(const Row& r) {
    SetRowSize(r.numCols);
    for (int i=0;i<numCols;i++)
    row[i]=r.row[i];
    return *this;
    }


    Again we return a reference, but this time it's a reference to itself. First we set the size of the current row equal to that of the source row, then we copy its values. There is an important note here. Notice that I'm using [] on the primitive T array itself--NOT the overloaded []s of Row. Remember that Row's [] returns a reference, thus if we had written row[i]=r[i], we would get a row that references the exact same data in memory, so that when we changed one the other would change--this isn't what we want at all, so we need to access the raw data in the Row class.

    Now we can write code like this:

    Row<double> r1(5);
    Row<double> r2;//creates an empty row
    Row<double> r3(2);
    r2=r1;
    r3=r1;//overwrites previous row information to contain same info as r1


    Matrices are Made of Many Rows
    Now that we have a working Row, we can combine rows into a matrix. Let's start with this basic definition:

    template<class T>
    class Matrix {
    public:
    Matrix(int rows=0, int cols=0): matrix(NULL) {
    SetSize(rows,cols);
    }
    Matrix(const Matrix& m): matrix(NULL) {
    SetSize(m.numRows,m.numCols);
    for (int r=0;r<numRows;r++)
    matrix[r]=Row<T>(m.matrix[r]);//assign to primitive array, NOT overloaded []--to get a copy
    }
    void SetSize(int rows, int cols) {
    if (rows) delete[]matrix;
    if (cols > 0 && rows >0) {
    matrix=new Row<T>[rows];
    for (int i=0;i<rows;i++)
    matrix[i].SetRowSize(cols);
    }
    else
    rows=NULL;
    numCols=cols;numRows=rows;
    }
    int GetCols() { return numCols;}
    int GetRows() { return numRows;}

    private:
    int numCols, numRows;
    Row<T>* matrix;

    };


    This follows very closely the basic form of the Row class. The only item of interest is when we declare and allocate a matrix: we must specify the type, T, after the class name.

    First let's implement the same operators we did on the Row class:

    Row<T>& operator[](int index) {
    assert(index<numRows);
    return matrix[index];
    }

    Matrix& operator=(const Matrix& m) {
    SetSize(m.numRows,m.numCols);
    for (int r=0;r<numRows;r++)
    matrix[r]=Row(m.matrix[r]);//assign to primitive array, NOT overloaded []--to get a copy
    return *this;
    }


    The most important part of this code is the return type of operator[]. It returns a reference to a Row of type T. This little fact allows us to use the Matrix class like this:

    Matrix<int> a(2,2);

    a[0][0]=2;
    a[0][1]=4;
    a[1][0]=8;
    a[1][1]=16;


    That is, we can refer to Matrix objects now with exactly the same notation as primitive 2-D arrays in C++: array[row][column]. Our operator overloading is faking it well enough to keep a consistent interface with analogous structures, but add much more functionality and safety. Isn't this cool?

    The = operator works the same way as in Row. It sets the size of the current Matrix to that of the source, and then copies all of the objects to the current Matrix. Now we can do the following:

    Matrix<__int64> m(1000,1000);
    Matrix<__int64> n=m;


    ...and we have two very large matrices of 64-bit integers.

    More C++ Articles
    More By Ben Watson


       · This example was very useful to me in both the operator over loading examples and...
       · opertor overloading is very important topic in c++i think it,s to understading...
       · Op overloading is a beginner's subject. Why use templates in a beginner level...
       · hi my name is shakil khan and i belong to swat pakistan.and i need full page about...
       · Operating overloading allows you to pass different variable types to the same...
     

    C++ ARTICLES

    - More Tricks to Gain Speed in Programming Con...
    - Easy and Efficient Programming for Contests
    - Preparing For Programming Contests
    - Programming Contests: Why Bother?
    - Polymorphism in C++
    - Overview of Virtual Functions
    - Inheritance in C++
    - Extending the Basic Streams in C++
    - Using Stringstreams in C++
    - Custom Stream Manipulation in C++
    - General Stream Manipulation in C++
    - Serialize Your Class into Streams in C++
    - Advanced File Handling with Streams in C++
    - File Handling and Streams in C++
    - The STL String Class







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    Stay green...Green IT