473,796 Members | 2,426 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

overloading the [] operator

Hello,

I've created a class to store 2 dimensional matrices, and I've been
trying to overload the [] operator, so access to the elements of the
matrix is easy. I have 3 private variables, _m, _row and _col which are
respectively the array to store the data in, the number of rows and the
number of columns. _m is of type T, and is size _row * _col * sizeof
(T).

I've managed to overload the subscript operator like this:
T & operator [] (int n)
{
return (_m[n * _col]);
}

but I don't understand why you can't do:
T * operator [] (int n)
{
return (&_m[n * _col]);
}

instead. The first one works fine, but with the second one when I try
something like m[0][0] = 100.0, m[0][0] comes up as being an invalid
lvalue.
Could someone help me out here?

Cheers,

- Joseph Paterson

Jun 3 '06 #1
16 2512
Joseph Paterson wrote:
Hello,

I've created a class to store 2 dimensional matrices, and I've been
trying to overload the [] operator, so access to the elements of the
matrix is easy. I have 3 private variables, _m, _row and _col which are
respectively the array to store the data in, the number of rows and the
number of columns. _m is of type T, and is size _row * _col * sizeof
(T).

I've managed to overload the subscript operator like this:
T & operator [] (int n)
{
return (_m[n * _col]);
}

but I don't understand why you can't do:
T * operator [] (int n)
{
return (&_m[n * _col]);
}

instead. The first one works fine, but with the second one when I try
something like m[0][0] = 100.0, m[0][0] comes up as being an invalid
lvalue.


Please, hit the FAQ. This topic has been beaten to death repeatedly in this
group and gives rise to a little bit flaming every once in a while. The
gist of it is:

a) Consider using operator()( row, col ) instead of operartor[][]. It is
easier to implement cleanly: the problem with [][]-syntax is that upon a
first try, you will settle on a quick and dirty solution where operator[]
return something like a vector (just as you indicate in your post). This is
bound to expose implementation details of the matrix class, which is
considered poor design. Details are in the FAQ.

b) If you are hard-headed / strongly-willed and determined to support the
[][]-syntax, overload operator[] to return a proxy object that contains a
reference to your matrix and knows the row. The proxy class itself will
overload operator[] (const) to return a (const) reference to the entry.
This trick allows to separate implementation and interface. Details are in
the FAQ.

c) If your matrix class aims to be more than merely a container, i.e., if
you plan on supporting linear algebra, please consider using one of the
many available libraries. A full-fledged matrix class is a project of
considerable size and difficulty. Don't call that upon yourself without
legitimate need unless you are looking for a character building and highly
educational exercise.
Best

Kai-Uwe Bux
Jun 3 '06 #2
I actually am trying to implement a fully fledged matrix class. I'm
starting on a graphics engine, and I want to fully support matrices and
all possible operations you can do on them :) It's fun, and a learning
experience.

I'll have a look at the FAQ - thanks!

- Joseph Paterson

Jun 3 '06 #3
Joseph Paterson wrote:
I actually am trying to implement a fully fledged matrix class.
Oh well.
I'm starting on a graphics engine, and I want to fully support matrices
and all possible operations you can do on them :) It's fun, and a learning
experience.
Ok, you asked for it:

a) You may want to read up on expression templates. When it comes to things
like adding vectors / matrices, the introduction of temporaries truly
becomes a performance issue. Expression templates are used in most state of
the art matrix libraries to deal with this problem. If you are really
headed for a graphics engine, performance will become an issue pretty soon.

b) As far as syntactic sugar (like [][]-notation) is concerned, I found that
the most interesting use of proxy classed for column and row vectors is to
support elementary operations like so:

A.row(i) += some_scalar * A.row(j);

or

swap( A.col(i), A.col(j) );

However, to make that work is a little bit challenging.

I'll have a look at the FAQ - thanks!


That is a good point to start. You may also want to pay attention to what it
has to say about floating point arithmetic (given that you are very likely
bound to do numerical linear algebra). Be warned that numerical linear
algebra is difficult and there are many traps (beyond the ones in the FAQ)
that are hard to spot. What looks like a correct algorithm from your Linear
Algebra text can turn out to be numerically unstable.
Have fun

Kai-Uwe Bux
Jun 3 '06 #4

Kai-Uwe Bux wrote:
Joseph Paterson wrote:
Hello,

I've created a class to store 2 dimensional matrices, and I've been
trying to overload the [] operator, so access to the elements of the
matrix is easy. I have 3 private variables, _m, _row and _col which are
respectively the array to store the data in, the number of rows and the
number of columns. _m is of type T, and is size _row * _col * sizeof
(T).

Please, hit the FAQ. This topic has been beaten to death repeatedly in this
group and gives rise to a little bit flaming every once in a while. The
gist of it is:


Yes, read the FAQ on why matrix shouldn't have [].

Also, I can't find it but it must be in the faq somewhere...all your
variable names are broken. Don't use anything that starts with an
underscore. An undercore *postfix* is now commonly used to identify
member variables...I don't personally see the need but if you do, think
about doing it that way...it won't run into conflicts with the std lib
or implementation.

Jun 3 '06 #5

Joseph Paterson wrote:
Hello,

I've created a class to store 2 dimensional matrices, and I've been
trying to overload the [] operator, so access to the elements of the
matrix is easy. I have 3 private variables, _m, _row and _col which are
respectively the array to store the data in, the number of rows and the
number of columns. _m is of type T, and is size _row * _col * sizeof
(T).

I've managed to overload the subscript operator like this:
T & operator [] (int n)
{
return (_m[n * _col]);
}

but I don't understand why you can't do:
T * operator [] (int n)
{
return (&_m[n * _col]);
}

instead. The first one works fine, but with the second one when I try
something like m[0][0] = 100.0, m[0][0] comes up as being an invalid
lvalue.
Could someone help me out here?


You are not providing enough information. The first should NOT work
and the second should based on my interpretation of your post. But I
don't know what _m is or what T is so I'm just guessing. At any rate,
I can't answer your question as I obviously don't understand the
problem.

Jun 3 '06 #6
Noah Roberts wrote:

Kai-Uwe Bux wrote:
Joseph Paterson wrote:
> Hello,
>
> I've created a class to store 2 dimensional matrices, and I've been
> trying to overload the [] operator, so access to the elements of the
> matrix is easy. I have 3 private variables, _m, _row and _col which are
> respectively the array to store the data in, the number of rows and the
> number of columns. _m is of type T, and is size _row * _col * sizeof
> (T).
[snip]
Also, I can't find it but it must be in the faq somewhere...all your
variable names are broken. Don't use anything that starts with an
underscore.

[reasonable recommendation snipped]

You cannot find it because it should not be there. The reserved identifiers
are [17.4.3.1.2]:

* any identifier that contains a *double* underscore "__".
* any identifier that begins with "_" followed by a *capital* letter.
* any identifier that begins with "_" is reserved in the *global namaspace*.

So, for local variables and parameters, the names are fine.

Best

Kai-Uwe
Jun 3 '06 #7
Kai-Uwe Bux wrote:
Noah Roberts wrote:

Kai-Uwe Bux wrote:
Joseph Paterson wrote:

> Hello,
>
> I've created a class to store 2 dimensional matrices, and I've been
> trying to overload the [] operator, so access to the elements of the
> matrix is easy. I have 3 private variables, _m, _row and _col which are
> respectively the array to store the data in, the number of rows and the
> number of columns. _m is of type T, and is size _row * _col * sizeof
> (T).

[snip]

Also, I can't find it but it must be in the faq somewhere...all your
variable names are broken. Don't use anything that starts with an
underscore.

[reasonable recommendation snipped]

You cannot find it because it should not be there. The reserved identifiers
are [17.4.3.1.2]:

* any identifier that contains a *double* underscore "__".
* any identifier that begins with "_" followed by a *capital* letter.
* any identifier that begins with "_" is reserved in the *global namaspace*.

So, for local variables and parameters, the names are fine.


You should never name a local variable with an underscore followed by
an upper case letter.
IAW C++ standards that you quoted, names that begin with an underscore
and are followed by an uppercase letter, can be used for anything by
the implementation.
That means the implementation can use macros for this.
Example:
#define _T(x) L##x

If you have a local variable with the name _T, it will fail to be
portable to an implementation that uses above macro.
IAW C++ standard, a name that begins with an underscore and then
followed by a lower case letter are reserved for the implementation in
the global namespace.
So technically speaking, IAW C++ standard, you could name a local
variable that begins with an underscore and is followed by a lower case
letter. And your code should be portable.

However, this is not true in practice, because some implementations
also use these types of names with macros, which invade all namespaces,
and not just the global namespace.
IAW with the C++ standard, the following code should be portable:
int foo(int _itot, int _ttoi)
{
return _itot + _ttoi;
}

But the above code is not portable to windows platform that reference
tchar.h, because this header has macros named _itot and _ttoi.

So I recommend that leading undescore not be used at all, even in local
variables.
It doesn't make the code work any better, and it can make your code
non-portable to some common implementations .

Jun 4 '06 #8
Joseph Paterson wrote:
Hello,

I've created a class to store 2 dimensional matrices, and I've been
trying to overload the [] operator, so access to the elements of the
matrix is easy. I have 3 private variables, _m, _row and _col which are
respectively the array to store the data in, the number of rows and the
number of columns. _m is of type T, and is size _row * _col * sizeof
(T).

I've managed to overload the subscript operator like this:
T & operator [] (int n)
{
return (_m[n * _col]);
}

but I don't understand why you can't do:
T * operator [] (int n)
{
return (&_m[n * _col]);
}

instead. The first one works fine, but with the second one when I try
something like m[0][0] = 100.0, m[0][0] comes up as being an invalid
lvalue.
Could someone help me out here?

It should be something like the following:
T* operator[](int n) {return m_ + (col_*n);}

Check out the following link for an example:
http://code.axter.com/dynamic_2d_array.h

Jun 4 '06 #9
Axter wrote:
Kai-Uwe Bux wrote:
Noah Roberts wrote:
>
> Kai-Uwe Bux wrote:
>> Joseph Paterson wrote:
>>
>> > Hello,
>> >
>> > I've created a class to store 2 dimensional matrices, and I've been
>> > trying to overload the [] operator, so access to the elements of the
>> > matrix is easy. I have 3 private variables, _m, _row and _col which
>> > are respectively the array to store the data in, the number of rows
>> > and the number of columns. _m is of type T, and is size _row * _col
>> > * sizeof (T). [snip]
>
> Also, I can't find it but it must be in the faq somewhere...all your
> variable names are broken. Don't use anything that starts with an
> underscore.

[reasonable recommendation snipped]

You cannot find it because it should not be there. The reserved
identifiers are [17.4.3.1.2]:

* any identifier that contains a *double* underscore "__".
* any identifier that begins with "_" followed by a *capital* letter.
* any identifier that begins with "_" is reserved in the *global
namaspace*.

So, for local variables and parameters, the names are fine.


You should never name a local variable with an underscore followed by
an upper case letter.

IAW C++ standards that you quoted, names that begin with an underscore
and are followed by an uppercase letter, can be used for anything by
the implementation.
That means the implementation can use macros for this.
Example:
#define _T(x) L##x

If you have a local variable with the name _T, it will fail to be
portable to an implementation that uses above macro.


Note: the names the OP used are not of this form! We are all in agreement
about names like "_T".

IAW C++ standard, a name that begins with an underscore and then
followed by a lower case letter are reserved for the implementation in
the global namespace.
So technically speaking, IAW C++ standard, you could name a local
variable that begins with an underscore and is followed by a lower case
letter. And your code should be portable.
That is why the OP's names are fine.
However, this is not true in practice, because some implementations
also use these types of names with macros, which invade all namespaces,
and not just the global namespace.
Those are broken implementations .
IAW with the C++ standard, the following code should be portable:
int foo(int _itot, int _ttoi)
{
return _itot + _ttoi;
}

But the above code is not portable to windows platform that reference
tchar.h, because this header has macros named _itot and _ttoi.
tchar.h is a not a standard header. If you use third-party libraries, all
sorts of new macros could be defined. No naming scheme will prevent clashes
with certainty.
So I recommend that leading undescore not be used at all, even in local
variables.
Although I would agree that the advice is sound and reasonable from a
practical point of view (and from an aesthetical angle, too: leading
underscores are plain ugly); I would also maintain that workarounds for
problems with tchar.h and other third-party headers are not exactly topical
in this group.
It doesn't make the code work any better, and it can make your code
non-portable to some common implementations .


Best

Kai-Uwe Bux
Jun 4 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
5248
by: | last post by:
Hi all, I've been using C++ for quite a while now and I've come to the point where I need to overload new and delete inorder to track memory and probably some profiling stuff too. I know that discussions of new and delete is a pretty damn involved process but I'll try to stick to the main information I'm looking for currently. I've searched around for about the last too weeks and have read up on new and overloading it to some extent but...
16
3099
by: gorda | last post by:
Hello, I am playing around with operator overloading and inheritence, specifically overloading the + operator in the base class and its derived class. The structure is simple: the base class has two int memebers "dataA", "dataB". The derived class has an additional int member "dataC". I am simply trying to overload the + operator so that 'adding' two objects will sum up the corresponding int members.
2
2068
by: pmatos | last post by:
Hi all, I'm overloading operator<< for a lot of classes. The question is about style. I define in each class header the prototype of the overloading as a friend. Now, where should I define the overloading of operator<<. In the .cc of the respective class or in a file where I am overloading operator<< for all classes? Cheers,
5
2490
by: luca regini | last post by:
I have this code class M { ..... T operator()( size_t x, size_t y ) const { ... Operator overloading A ....} T& operator()( size_t x, size_t y )
2
2262
by: brzozo2 | last post by:
Hello, this program might look abit long, but it's pretty simple and easy to follow. What it does is read from a file, outputs the contents to screen, and then writes them to a different file. It uses map<and heavy overloading. The problem is, the output file differs from input, and for the love of me I can't figure out why ;p #include <iostream> #include <fstream> #include <sstream>
5
3632
by: Jerry Fleming | last post by:
As I am newbie to C++, I am confused by the overloading issues. Everyone says that the four operators can only be overloaded with class member functions instead of global (friend) functions: (), , ->, =. I wonder why there is such a restriction. Some tutorials say that 'new' and 'delete' can only be overloaded with static member functions, others say that all overloading function should be non-static. Then what is the fact, and why? ...
3
3284
by: y-man | last post by:
Hi, I am trying to get an overloaded operator to work inside the class it works on. The situation is something like this: main.cc: #include "object.hh" #include "somefile.hh" object obj, obj2 ;
9
3517
by: sturlamolden | last post by:
Python allows the binding behaviour to be defined for descriptors, using the __set__ and __get__ methods. I think it would be a major advantage if this could be generalized to any object, by allowing the assignment operator (=) to be overloaded. One particular use for this would be to implement "lazy evaluation". For example it would allow us to get rid of all the temporary arrays produced by NumPy. For example, consider the...
2
4443
by: Colonel | last post by:
It seems that the problems have something to do with the overloading of istream operator ">>", but I just can't find the exact problem. // the declaration friend std::istream & operator>(std::istream & in, const Complex & a); // the methods correspond to the friend std::istream & operator>(std::istream & in, const Complex & a) { std::cout << "real: ";
8
2977
by: Wayne Shu | last post by:
Hi everyone, I am reading B.S. 's TC++PL (special edition). When I read chapter 11 Operator Overloading, I have two questions. 1. In subsection 11.2.2 paragraph 1, B.S. wrote "In particular, operator =, operator, operator(), and operator-must be nonstatic member function; this ensures that their first operands will be lvalues". I know that these operators must be nonstatic member functions, but why this ensure their first operands will...
0
9680
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9528
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10456
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10174
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10012
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7548
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5575
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4118
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2926
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.