what's different b/w two overloaded "operator ()" in a matriximplementation?

Z

z65536

Hello All!
I came across a class declaration for a Matrix class (in the book: C++
primer), in which are two overloaded methods for "operator ()"

The prototypes:

class Matrix{
public:
int &operator () (int, int);
int operator() (int, int) const;
...
}


The questions are:
1. Why do we need two? When they are invoked from the client, do they
look the same? (I think so)
2. How do they differ from each other in term of semantic?


Thanks to all!
hai
 
S

SG

Hello All!
I came across a class declaration for a Matrix class [...]
in which are two overloaded methods for "operator ()"

class Matrix{
public:
  int& operator() (int, int); // #1
  int operator() (int, int) const; // #2
  ...
};

The questions are:
1. Why do we need two? When they are invoked from the client,
do they look the same? (I think so)
2. How  do they differ from each other in term of semantic?

You need two versions if you want to allow users to assign new values
to the matrix' entries and to access the elements using a reference to
a const matrix:

void alter(Matrix & m)
{
m(0,0) = 23; // picks #1
}

void show(Matrix const& m)
{
cout << m(0,0); // picks #2
// m(0,0) = 9; would not work
// because #2 results in an rvalue
}

Cheers,
SG
 
P

Paul N

Hello All!
I came across a class declaration for a Matrix class (in the book: C++
primer), in which are two overloaded methods for "operator ()"

The prototypes:

class Matrix{
public:
  int &operator () (int, int);
  int operator() (int, int) const;
  ...

}

The questions are:
1. Why do we need two? When they are invoked from the client, do they
look the same? (I think so)
2. How  do they differ from each other in term of semantic?

Thanks to all!
hai

Hi!

I'd recommend reading the FAQ (Frequently Asked Questions), which you
can find at http://www.parashift.com/c++-faq-lite . It has lots of
good stuff in it, including (at 18.12) some stuff relating to the one
you asked.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,739
Latest member
Clint8040

Latest Threads

Top