473,394 Members | 1,794 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

overloading [][]

Hi,

I have a class which contains a two-dimensional array. I need to
overload something like the [][] operator so that I'm able to access the
internal array elements via the class object. For example:

Matrix a = new Matrix(10,10);

a[1][1] = 6;

Is this possible? How can I simulate a two dimensional array using a
class in c++? Thanks

-Andre

Jul 19 '05 #1
11 7030

"Andre" <fo********@hotmail.com> wrote in message
news:3f******@clarion.carno.net.au...
Hi,

I have a class which contains a two-dimensional array. I need to
overload something like the [][] operator so that I'm able to access the
internal array elements via the class object. For example:

Matrix a = new Matrix(10,10);

a[1][1] = 6;

Is this possible? How can I simulate a two dimensional array using a
class in c++? Thanks

-Andre


There is no operator[][], there is only the operator[]. You can do what you
want with a proxy class, something like this

class Proxy
{
public:
double operator[](int j) const;
double& operator[](int j);
};

class Matrix
{
public:
const Proxy operator[](int i) const;
Proxy operator[](int i);
};

I hope you get the idea, you overload operator[] on your Matrix object to
return another class (the Proxy class), you then overload operator[] on the
proxy class to return a Matrix element.

john
Jul 19 '05 #2
Neat :) thatnks, I get the idea.

cheers

-Andre

John Harrison wrote:
"Andre" <fo********@hotmail.com> wrote in message
news:3f******@clarion.carno.net.au...
Hi,

I have a class which contains a two-dimensional array. I need to
overload something like the [][] operator so that I'm able to access the
internal array elements via the class object. For example:

Matrix a = new Matrix(10,10);

a[1][1] = 6;

Is this possible? How can I simulate a two dimensional array using a
class in c++? Thanks

-Andre

There is no operator[][], there is only the operator[]. You can do what you
want with a proxy class, something like this

class Proxy
{
public:
double operator[](int j) const;
double& operator[](int j);
};

class Matrix
{
public:
const Proxy operator[](int i) const;
Proxy operator[](int i);
};

I hope you get the idea, you overload operator[] on your Matrix object to
return another class (the Proxy class), you then overload operator[] on the
proxy class to return a Matrix element.

john


Jul 19 '05 #3
Sim
Just wondering.. what does they "const" in front of a function do:

double operator[](int j) const;

Thanks

Sim
John Harrison wrote:
"Andre" <fo********@hotmail.com> wrote in message
news:3f******@clarion.carno.net.au...
Hi,

I have a class which contains a two-dimensional array. I need to
overload something like the [][] operator so that I'm able to access the
internal array elements via the class object. For example:

Matrix a = new Matrix(10,10);

a[1][1] = 6;

Is this possible? How can I simulate a two dimensional array using a
class in c++? Thanks

-Andre

There is no operator[][], there is only the operator[]. You can do what you
want with a proxy class, something like this

class Proxy
{
public:
double operator[](int j) const;
double& operator[](int j);
};

class Matrix
{
public:
const Proxy operator[](int i) const;
Proxy operator[](int i);
};

I hope you get the idea, you overload operator[] on your Matrix object to
return another class (the Proxy class), you then overload operator[] on the
proxy class to return a Matrix element.

john


Jul 19 '05 #4

"Sim" <si***@no.com> wrote in message
news:3f********@clarion.carno.net.au...
Just wondering.. what does they "const" in front of a function do:

double operator[](int j) const;

Thanks

Sim


It means that the function does not modify the object and therefore that the
function can be called on a const object.

E.g.

struct X
{
void f();
void g() const;
};

const X x;
x.f(); // error
x.g(); // ok

Functions which do not modify objects should almost always be declared
const. const objects don't get used much, but const references are very
common.

john
Jul 19 '05 #5
"John Harrison" <jo*************@hotmail.com> wrote in
news:bi************@ID-196037.news.uni-berlin.de:

"Andre" <fo********@hotmail.com> wrote in message
news:3f******@clarion.carno.net.au...
Hi,

I have a class which contains a two-dimensional array. I need to
overload something like the [][] operator so that I'm able to access
the internal array elements via the class object. For example:

Matrix a = new Matrix(10,10);

a[1][1] = 6;

Is this possible? How can I simulate a two dimensional array using a
class in c++? Thanks

-Andre

There is no operator[][], there is only the operator[]. You can do
what you want with a proxy class, something like this

class Proxy
{
public:
double operator[](int j) const;

const double& double& operator[](int j);
};

class Matrix
{
public:
const Proxy operator[](int i) const; ^^^^^
const Proxy & and Proxy operator[](int i); Proxy& will have better performance, plus, you can have the
proxyclass save a reference to your data matrix-row and I would make this
class inside the Matrix namespace to avoid name collisions with other
Proxy classes for different multi-dimensional arrays. };


References combined with inline functions will have improved performance,
since there will be no copy-constructor and destructor calls, less
overhead.
Jul 19 '05 #6
Sim
Thanks. That clears it :-)

Sim

Gianni Mariani wrote:
Sim wrote:
Just wondering.. what does they "const" in front of a function do:

double operator[](int j) const;

It declares that the method does not alter any "non mutable" object state.

e.g.

struct A {
int a;
mutable int b;
void doer_a() const
{
a = 3; // illegal;
}
void doer_b() const
{
b = 3; // legal;
}
};


Jul 19 '05 #7
Sim
The topic seemed interesting so I gave it a try myself. I can't get my
proxy class running. I get a number of errors when I do something like:

matrixA[0][0] = 5.0;

or std::cout << matrixA[0][0];

I simply did a:

const Proxy operator[](int i) const {
return this->proxy[i];
}

Proxy operator[](int i) {
return this->proxy[i];
}

and in proxy I did:

double operator[](int j) const {
return matrix->[j];
}
double& operator[](int j) {
return matrix->[j];
}

and I had my two-dim array in the proxy class:

double **matrix;
What am I doing wrong? Andre if you got it working could you help me out?

thanks

Sim
Immanuel Albrecht wrote:
"John Harrison" <jo*************@hotmail.com> wrote in
news:bi************@ID-196037.news.uni-berlin.de:

"Andre" <fo********@hotmail.com> wrote in message
news:3f******@clarion.carno.net.au...
Hi,

I have a class which contains a two-dimensional array. I need to
overload something like the [][] operator so that I'm able to access
the internal array elements via the class object. For example:

Matrix a = new Matrix(10,10);

a[1][1] = 6;

Is this possible? How can I simulate a two dimensional array using a
class in c++? Thanks

-Andre


There is no operator[][], there is only the operator[]. You can do
what you want with a proxy class, something like this

class Proxy
{
public:
double operator[](int j) const;


const double&
double& operator[](int j);
};

class Matrix
{
public:
const Proxy operator[](int i) const;


^^^^^
const Proxy & and
Proxy operator[](int i);


Proxy& will have better performance, plus, you can have the
proxyclass save a reference to your data matrix-row and I would make this
class inside the Matrix namespace to avoid name collisions with other
Proxy classes for different multi-dimensional arrays.
};

References combined with inline functions will have improved performance,
since there will be no copy-constructor and destructor calls, less
overhead.


Jul 19 '05 #8

"Immanuel Albrecht" <xr*****@gmx.de> wrote in message
news:bi*************@news.t-online.com...
"John Harrison" <jo*************@hotmail.com> wrote in
news:bi************@ID-196037.news.uni-berlin.de:

"Andre" <fo********@hotmail.com> wrote in message
news:3f******@clarion.carno.net.au...
Hi,

I have a class which contains a two-dimensional array. I need to
overload something like the [][] operator so that I'm able to access
the internal array elements via the class object. For example:

Matrix a = new Matrix(10,10);

a[1][1] = 6;

Is this possible? How can I simulate a two dimensional array using a
class in c++? Thanks

-Andre


There is no operator[][], there is only the operator[]. You can do
what you want with a proxy class, something like this

class Proxy
{
public:
double operator[](int j) const;

const double&
double& operator[](int j);
};

class Matrix
{
public:
const Proxy operator[](int i) const;

^^^^^
const Proxy & and
Proxy operator[](int i);

Proxy& will have better performance,


If you return a reference, then you have to have an object to refer to.
Where do you propose to store that object? I think its well known that this
scheme is impossible to implement correctly and safely. See for instance
Effective C++ by Scott Meyer who gives all the various flawed possibilities
a good going over.

Unless of course you have some code that shows differently ...

john
Jul 19 '05 #9

"Sim" <si***@no.com> wrote in message
news:3f********@clarion.carno.net.au...
The topic seemed interesting so I gave it a try myself. I can't get my
proxy class running. I get a number of errors when I do something like:

matrixA[0][0] = 5.0;

or std::cout << matrixA[0][0];

I simply did a:

const Proxy operator[](int i) const {
return this->proxy[i];
}

Proxy operator[](int i) {
return this->proxy[i];
}

and in proxy I did:

double operator[](int j) const {
return matrix->[j];
}
double& operator[](int j) {
return matrix->[j];
}

and I had my two-dim array in the proxy class:

double **matrix;
What am I doing wrong? Andre if you got it working could you help me out?

Well the two dim array is supposed to be in the Matrix class. The proxy
class just hold a reference to the matrix and the first index.

Something like this (untested code)

class Matrix;

class Proxy
{
friend class Matrix;
double& operator[](int j) { return m.matrix[i][j]; }
private:
Proxy(Matrix& mm, int ii) : m(mm), i(ii) {}
Matrix& m;
int i;
};

class Matrix
{
friend class Proxy;
public:
Proxy operator[](int i) { return Proxy(*this, i); }
private:
double** matrix;
};

Basically the Proxy class just holds the parameters used in the first
operator[] call, so that when the second operator[] call happens they are
available to get the element from the Matrix.

john
thanks

Sim
Immanuel Albrecht wrote:
"John Harrison" <jo*************@hotmail.com> wrote in
news:bi************@ID-196037.news.uni-berlin.de:

"Andre" <fo********@hotmail.com> wrote in message
news:3f******@clarion.carno.net.au...

Hi,

I have a class which contains a two-dimensional array. I need to
overload something like the [][] operator so that I'm able to access
the internal array elements via the class object. For example:

Matrix a = new Matrix(10,10);

a[1][1] = 6;

Is this possible? How can I simulate a two dimensional array using a
class in c++? Thanks

-Andre
There is no operator[][], there is only the operator[]. You can do
what you want with a proxy class, something like this

class Proxy
{
public:
double operator[](int j) const;


const double&
double& operator[](int j);
};

class Matrix
{
public:
const Proxy operator[](int i) const;


^^^^^
const Proxy & and
Proxy operator[](int i);


Proxy& will have better performance, plus, you can have the
proxyclass save a reference to your data matrix-row and I would make this class inside the Matrix namespace to avoid name collisions with other
Proxy classes for different multi-dimensional arrays.
};

References combined with inline functions will have improved performance, since there will be no copy-constructor and destructor calls, less
overhead.

Jul 19 '05 #10
"John Harrison" <jo*************@hotmail.com> wrote in
news:bi************@ID-196037.news.uni-berlin.de:

First of all, sorry for being late, I was at vacation...
If you return a reference, then you have to have an object to refer
to. Where do you propose to store that object? Of course, in your Matrix class your object should be stored. I think its well known
that this scheme is impossible to implement correctly and safely. See
for instance Effective C++ by Scott Meyer who gives all the various
flawed possibilities a good going over.
I'm sorry, but I haven't read this book.
Unless of course you have some code that shows differently ...


So what's wrong with e.g. this:
#include <iostream>
#include <ostream>

#include <vector>

template <int rows,int cols> class Matrix
{
private:
double mat[rows][cols];
public:
class Proxy {
private:
Matrix* m;
int row;

friend class Matrix;

void SetRow(int r)
{ row = r;}

void SetMat(Matrix* matrix)
{ m = matrix;}

public:
Proxy() {}

const double& operator [](int i) const;
double& operator [](int i);

};

friend class Proxy;
private:
std::vector<Proxy> prox;

public:

Matrix() : prox(rows)
{
for (unsigned int r=0;r<rows;r++)
{
prox[r].SetRow(r);
prox[r].SetMat(this);
}
}

const Proxy& operator[] (int i) const
{
return prox[i];
}

Proxy& operator[] (int i)
{
return prox[i];
}

};

template <int rows, int cols>
const double& Matrix<rows,cols>::Proxy::operator[](int i) const
{
return m->mat[row][i];
}

template <int rows, int cols>
double& Matrix<rows,cols>::Proxy::operator[](int i)
{
return m->mat[row][i];
}

int main()
{
Matrix<4,4> m;

for (unsigned int r=0;r<4;r++)
for (unsigned int c=0;c<4;c++)
{
std::cout << r << " " << c <<std::endl;
m[r][c] = r+c;
}

for (unsigned int r=0;r<4;r++)
{
for (unsigned int c=0;c<4;c++)
std::cout << m[r][c] << " ";

std::cout << std::endl;
}
return 0;
}
Jul 19 '05 #11

"Immanuel Albrecht" <xr*****@gmx.de> wrote in message
news:bi*************@news.t-online.com...
"John Harrison" <jo*************@hotmail.com> wrote in
news:bi************@ID-196037.news.uni-berlin.de:

First of all, sorry for being late, I was at vacation...
If you return a reference, then you have to have an object to refer
to. Where do you propose to store that object?

Of course, in your Matrix class your object should be stored.
I think its well known
that this scheme is impossible to implement correctly and safely. See
for instance Effective C++ by Scott Meyer who gives all the various
flawed possibilities a good going over.


I'm sorry, but I haven't read this book.

Unless of course you have some code that shows differently ...


So what's wrong with e.g. this:
#include <iostream>
#include <ostream>

#include <vector>

template <int rows,int cols> class Matrix
{
private:
double mat[rows][cols];
public:
class Proxy {
private:
Matrix* m;
int row;

friend class Matrix;

void SetRow(int r)
{ row = r;}

void SetMat(Matrix* matrix)
{ m = matrix;}

public:
Proxy() {}

const double& operator [](int i) const;
double& operator [](int i);

};

friend class Proxy;
private:
std::vector<Proxy> prox;

public:

Matrix() : prox(rows)
{
for (unsigned int r=0;r<rows;r++)
{
prox[r].SetRow(r);
prox[r].SetMat(this);
}
}

const Proxy& operator[] (int i) const
{
return prox[i];
}

Proxy& operator[] (int i)
{
return prox[i];
}

};

template <int rows, int cols>
const double& Matrix<rows,cols>::Proxy::operator[](int i) const
{
return m->mat[row][i];
}

template <int rows, int cols>
double& Matrix<rows,cols>::Proxy::operator[](int i)
{
return m->mat[row][i];
}

int main()
{
Matrix<4,4> m;

for (unsigned int r=0;r<4;r++)
for (unsigned int c=0;c<4;c++)
{
std::cout << r << " " << c <<std::endl;
m[r][c] = r+c;
}

for (unsigned int r=0;r<4;r++)
{
for (unsigned int c=0;c<4;c++)
std::cout << m[r][c] << " ";

std::cout << std::endl;
}
return 0;
}


Well you've answered my point
If you return a reference, then you have to have an object to refer
to. Where do you propose to store that object?


by creating a vector of proxys. But that's an overhead for every matrix to
carry around. Arguably its a small amount of space compared to the matrix as
a whole. Whether your method is better than copying the Proxy class as I
suggested would depend on the application I think. In any case, as John
Carson pointed out, this time the proxy class need only be a pointer, which
is better than both our methods.

john
Jul 19 '05 #12

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

Similar topics

17
by: Terje Slettebų | last post by:
To round off my trilogy of "why"'s about PHP... :) If this subject have been discussed before, I'd appreciate a pointer to it. I again haven't found it in a search of the PHP groups. The PHP...
4
by: Dave Theese | last post by:
Hello all, I'm trying to get a grasp of the difference between specializing a function template and overloading it. The example below has a primary template, a specialization and an overload. ...
5
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...
39
by: zeus | last post by:
I know function overloading is not supported in C. I have a few questions about this: 1. Why? is it from technical reasons? if so, which? 2. why wasn't it introduced to the ANSI? 3. Is there any...
45
by: JaSeong Ju | last post by:
I would like to overload a C function. Is there any easy way to do this?
31
by: | last post by:
Hi, Why can I not overload on just the return type? Say for example. public int blah(int x) { }
2
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...
15
by: lordkain | last post by:
is it possible to do some kind of function overloading in c? and that the return type is different
11
by: placid | last post by:
Hi all, Is it possible to be able to do the following in Python? class Test: def __init__(self): pass def puts(self, str): print str
10
by: Matthew | last post by:
Am I correct in thinking there is no method/function overloading of any kind in any version of PHP? Thanks, Matthew
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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,...

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.