Thread: Parenthesis operator overload

  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    71

    Parenthesis operator overload

    I was trying to implement a simple matrix class below is its code. Can any one tell me why the the print statement "CALLED CONST" isn't getting executed ? It was supposed to get printed while executing these two statements .
    Code:
    	int x=M(3,4)+5;
    	cout<<M(3,4)<<endl;
    Can someone help ?
    Code:
    #include <cstdio>
    #include <vector>
    #include <iostream>
    #include <algorithm>
    using namespace std;
    
    template<class T>
    class Matrix
    {
    	private:
    	unsigned r,c; 
    	vector<T>data;
    
    	public:
    	Matrix(){};
    	Matrix(unsigned _r,unsigned _c):r(_r),c(_c)
    	{
    		data.resize(r*c);
    	}
    	T& operator ()(unsigned _r,unsigned _c)
    	{
    		puts("CALLED");
    		return data[c*_r+_c];
    	}
    	T operator ()(unsigned _r,unsigned _c) const
    	{
    		puts("CALLED CONST");
    		return data[c*_r+_c];
    	}
    };
    
    int main()
    {
    	Matrix<int>M(5,5);
    	M(3,4)=19191;
    	int x=M(3,4)+5;
    	cout<<M(3,4)<<endl;
    	return 0;
    }

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    The compiler doesn't choose between the const and non-const overload based on your usage.

    It chooses based on whether the instance is const or not.

    Code:
    int main()
    {
    	Matrix<int>M(5,5);
    	M(3,4)=19191;
    
            const Matrix<int>& N = M;
    	int x=N(3,4)+5;        
    	cout<<N(3,4)<<endl;
    	return 0;
    }
    BTW, your const overload should better return a const T (or a const T&). Otherwise the following will compile for user-defined types, but will only result in modifying a temporary.
    Code:
    	const Matrix<std::string>N(5,5);
    	N(3, 4) = "Hello";
    Last edited by anon; 04-13-2011 at 08:50 AM.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  3. #3
    Registered User
    Join Date
    Jan 2009
    Posts
    71
    Thank you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. overload operator[] help please
    By ychen42 in forum C++ Programming
    Replies: 12
    Last Post: 11-10-2010, 08:03 PM
  2. Operator overload
    By Gordon in forum C++ Programming
    Replies: 3
    Last Post: 03-11-2008, 01:20 PM
  3. Overload operator
    By verbity in forum C++ Programming
    Replies: 13
    Last Post: 03-30-2007, 11:00 AM
  4. overload operator<
    By Unregistered in forum C++ Programming
    Replies: 3
    Last Post: 12-12-2001, 03:54 PM
  5. Overload (+) operator
    By kit in forum C++ Programming
    Replies: 8
    Last Post: 10-23-2001, 11:20 AM