473,804 Members | 3,113 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

operator overloading

i have studied this example of overloading [] operator, but i don`t
know exactly what happened in code .kindly explain me:

#include <iostream>
using namespace std;
const int SIZE = 3;
class atype {
int a[SIZE];
public:
atype() {
register int i;
for(i=0; i<SIZE; i++) a[i] = i;
}
int &operator[](int i) {return a[i];}
};
int main()
{
atype ob;
cout << ob[2]; // displays 2
cout << " ";
ob[2] = 25; // [] on left of =
cout << ob[2]; // now displays 25
return 0;
}
..rest code is ok.what happened in this line of code and how
ob[2] = 25;
what it mean? is it mean ob.a[2]=25 ? kindly explain.

May 17 '07 #1
5 5436
"ashu" writes:
>Ii have studied this example of overloading [] operator, but i don`t
know exactly what happened in code .kindly explain me:

#include <iostream>
using namespace std;
const int SIZE = 3;
class atype {
int a[SIZE];
public:
atype() {
register int i;
for(i=0; i<SIZE; i++) a[i] = i;
}
int &operator[](int i) {return a[i];}
This has the same effect as
int& bracket(int)
{
return a[i];
}

where the word bracket replaces the glyphs for brackets in the original

};
int main()
{
atype ob;
cout << ob[2]; // displays 2
cout << " ";
ob[2] = 25; // [] on left of =
cout << ob[2]; // now displays 25
return 0;
}
You do realize, I hope, that the example is pointless, it is simply provided
to show you the syntax?. The constructor sets
a[k] = k for all elements in the array,
but I think you already knew that.
.rest code is ok.what happened in this line of code and how
ob[2] = 25;
what it mean? is it mean ob.a[2]=25 ? kindly explain.

May 18 '07 #2
"osmium" wrote:
>This has the same effect as
int& bracket(int)
Oops! should be

int& bracket(int i)
{
return a[i];
}

May 18 '07 #3
On May 17, 4:29 pm, "osmium" <r124c4u...@com cast.netwrote:
"osmium" wrote:
This has the same effect as
int& bracket(int)

Oops! should be

int& bracket(int i)
{
return a[i];
}
may someone is kind enough to give me indepth knowledge of operator
overloading specially- [],(),comma opeartor,new and delete.

May 18 '07 #4
ashu wrote:
On May 17, 4:29 pm, "osmium" <r124c4u...@com cast.netwrote:
>"osmium" wrote:
>>This has the same effect as
int& bracket(int)
Oops! should be

int& bracket(int i)
>> {
return a[i];
}

may someone is kind enough to give me indepth knowledge of operator
overloading specially- [],(),comma opeartor,new and delete.
Read Stroustrup chapter 11.

--
Ian Collins.
May 18 '07 #5
"ashu" writes:
may someone is kind enough to give me indepth knowledge of operator
overloading specially- [],(),comma opeartor,new and delete.
The hard copy of the Eckel book I have has syntax for, AFAIK, *all* the
operators that can be overloaded. The book is free on line, I dislike
E-books so I didn't confirm that all that excruciating detail is in the
E-book The examples are similar to what you posted - no obvious practical
usage.

Here is a somewhat more useful example of using the [] operator, it gives
you an array that has bounds checking, something lacking in C - but
available if you jump through the right hoops in C++. In a real program it
should "throw" an error instead of printing an error message.. Doing so
here would simply obscure the point of the code.

To use, remove the STOP macros where they appear in the body of the code -
they are there to humor my compiler.

/* 070517 demonstrate overloading of [] operator
Create an array of int with 10 elements and detect
out of range errors */

#include <iostream>

#define STOP while(1) cin.get();

using namespace std;

class Arr
{
public:
int& operator[] (int);
private:
enum{K=10};
int a[K];
};
//............... .............
int& Arr::operator[] (int i)
{
if(i<0 || i>9)
{
cout << "Subscript out of range in class Arr\n"
<< "Valid range is 0..9 and value provided was "
<< i << endl;
STOP;
exit(1);
}
return a[i];
}
//==============
int main()
{
Arr arr;
for(int j=0; j<10; j++)
arr[j] = 100 + j;
for(int k=0; k<10; k++)
cout << arr[k] << endl;
// next two cause error messages
//cout << arr[-1] << endl;
//cout << arr[10] << endl;

STOP;
}
May 18 '07 #6

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

Similar topics

16
2623
by: Edward Diener | last post by:
Is there a way to override the default processing of the assignment operator for one's own __value types ? I realize I can program my own Assign method, and provide that for end-users of my class, but I would like to use internally my own = operator for some of my value types, so I can say "x = y;" rather than "x.Assign(y);". The op_Assign operator seems impossibly broken since it takes __value copies of the two objects. Perhaps there is...
34
6474
by: Pmb | last post by:
I've been working on creating a Complex class for my own learning purpose (learn through doing etc.). I'm once again puzzled about something. I can't figure out how to overload the assignment operator. Here's what I'm trying to do. I've defined class Complex as class Complex { friend ostream &operator<<( ostream &, Complex & ); public: Complex( float = 0.0, float = 0.0 );
16
3100
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
2070
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,
67
8673
by: carlos | last post by:
Curious: Why wasnt a primitive exponentiation operator not added to C99? And, are there requests to do so in the next std revision? Justification for doing so: C and C++ are increasingly used in low-level numerical computations, replacing Fortran in newer projects. Check, for example, sourceforge.net or freshmeat.net But neither language offers a primitive exp operator.
3
2302
by: karthik | last post by:
The * operator behaves in 2 different ways. It is used as the value at address operator as well as the multiplication operator. Does this mean * is overloaded in c?
5
3634
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
3285
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
3519
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...
8
2979
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
9706
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
10578
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...
0
10332
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10321
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
10077
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
7620
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
6853
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4300
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
2
3820
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.