Skip to main content
gamedev.net
🔒 Locked

Operator overloading

Started by Alexistran 4 replies 550+ views
Original Post
Alexistran
Alexistran
I have a Matrix class which is a 2D array of doubles, I was wondering if it were possible to overload the [] operator to access both row and column in the Matrix ie. Matrix a; a[1][1] = 5.0; I know its possible to overload the [] operator but I'm not sure for a matrix.
Alexistran
Alexistran
Thanks.

Another quick question:


double& operator() (unsigned row, unsigned col); ← subscript operators often come in pairs
double operator() (unsigned row, unsigned col) const;


Any particular reason for the second one? I normally do, do operators in pairs but one is of the new data type and the other is an existing one
Vorpy
Vorpy
One of them is const, the other isn't. The data members of a const object are treated as const and only const functions of the object are allowed to be called. The two versions of the operator are to allow the returned value (which is a reference to a value inside the object) to be altered when the object is const and to still allow the value to be accessed (but not altered) when the object is const.

For primitive types and small objects you can return a copy of the data for the const version. For more complicated types where there may be more overhead involved with copying the const version usually returns a const reference.
snk_kid
snk_kid
If you are dealing with fixed-sized vectors & matrices (2/3/4d) then you might be interested in this
Zahlman
Zahlman
Quote:
Original post by Alexistran
Thanks.

Another quick question:


double& operator() (unsigned row, unsigned col); ← subscript operators often come in pairs
double operator() (unsigned row, unsigned col) const;


Any particular reason for the second one?


...

Yes.
The text "subscript operators often come in pairs", in the original context, is linked. Follow the link.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.