473,378 Members | 1,384 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,378 software developers and data experts.

Overload Operators for referenced objects?

hello,

somehow i can't figure out, how to overload the [] operator for a referenced
object. if i have

class MyClass {

int operator[](int i) { return 1; };

};

....

MyClass* oskar = new MyClass();
cout << oskar[3];
delete oskar;

the compiler says "cannot convert ‘OperatorSequence’ to ‘int’ in
initialization". with

MyClass oskar;

it works, though. how can i use the overloaded [] for pointers? i also need
to overload arithmetic operations in my class, is there a similar problem
when dealing with referenced objects?

thanks in advance and greetings, jonas
Feb 11 '07 #1
6 1786
Jonas Huckestein wrote:
hello,

somehow i can't figure out, how to overload the [] operator for a
referenced object. if i have

class MyClass {

int operator[](int i) { return 1; };

};

...

MyClass* oskar = new MyClass();
cout << oskar[3];
delete oskar;

the compiler says "cannot convert ‘OperatorSequence’ to ‘int’ in
initialization".
The compiler probably wants to say that it can't find an operator << that
takes a MyClass object. oskar[3] ist the same as *(oskar+3), expecting that
oskar is the pointer to the start of an array of MyClass, and you wan the
3rd element of that array.
with

MyClass oskar;

it works, though. how can i use the overloaded [] for pointers?
You are using it, but I guess you actually don't want to. If you want to use
the [] operator of your class instead of the one for pointers, you have to
dereference first:

cout << (*oskar)[3];
i also need to overload arithmetic operations in my class, is there a
similar problem when dealing with referenced objects?
Well, if you use a pointer, the operators for pointers will be used.

Feb 11 '07 #2
Jonas Huckestein wrote:
hello,

somehow i can't figure out, how to overload the [] operator for a
referenced object. if i have

class MyClass {

int operator[](int i) { return 1; };
You might want to consider using std::size_t instead of int as the argument
type.
>
};

...

MyClass* oskar = new MyClass();
cout << oskar[3];
Two options:

oskar->operator[](3)

or (more readable):

(*oskar)[3]

delete oskar;

the compiler says "cannot convert ?OperatorSequence? to ?int? in
initialization". with

MyClass oskar;

it works, though. how can i use the overloaded [] for pointers? i also
need to overload arithmetic operations in my class, is there a similar
problem when dealing with referenced objects?
The problem is that you don't distinguish between the pointer and the
pointee. If you want to add the pointees, you have to get them first by
dereferencing the pointer. The problem is totally unrelated to your class,
you would face it with pointers of type int* just as well.
int* ap = new int ( 5 );
int* bp = new int ( 6 ); // warning: already possibly leaking ap.
ap + bp; // bogus: trying to add two pointers
*ap + *bp; // ok: adding pointees.
delete ap;
delete bp;
Best

Kai-Uwe Bux
Feb 11 '07 #3
Jonas Huckestein wrote:
hello,

somehow i can't figure out, how to overload the [] operator for a referenced
object. if i have

class MyClass {

int operator[](int i) { return 1; };

};

...

MyClass* oskar = new MyClass();
cout << oskar[3];
delete oskar;

the compiler says "cannot convert ‘OperatorSequence’ to ‘int’ in
initialization". with

MyClass oskar;

it works, though. how can i use the overloaded [] for pointers? i also need
to overload arithmetic operations in my class, is there a similar problem
when dealing with referenced objects?

thanks in advance and greetings, jonas

Because you're applying it to a pointer, not a reference or an object.

MyClass oskar;
cout << oskar[3];
Feb 11 '07 #4
Jonas Huckestein wrote:
hello,

somehow i can't figure out, how to overload the [] operator for a referenced
object. if i have

class MyClass {

int operator[](int i) { return 1; };

};

...

MyClass* oskar = new MyClass();
cout << oskar[3];
delete oskar;

the compiler says "cannot convert ‘OperatorSequence’ to ‘int’ in
initialization". with

MyClass oskar;

it works, though. how can i use the overloaded [] for pointers? i also need
to overload arithmetic operations in my class, is there a similar problem
when dealing with referenced objects?

thanks in advance and greetings, jonas

You cannot overload operator[] for pointers, you cannot overload any
pointer operator.

It sounds like you want a class that overload several operators but
behaves like a pointer otherwise. Well, that is what you must write

class MyPtrClass
{
public:
int operator[](int i);
// etc...
private:
MyClass* ptr;
};

In other words write a class that contains a single pointer to another
class, and put the overloaded operators there.

john
Feb 11 '07 #5

"Kai-Uwe Bux" <jk********@gmx.netwrote in message
news:eq**********@murdoch.acc.Virginia.EDU...
Jonas Huckestein wrote:
>hello,

somehow i can't figure out, how to overload the [] operator for a
referenced object. if i have

class MyClass {

int operator[](int i) { return 1; };

You might want to consider using std::size_t instead of int as the
argument
type.
Yes you would think that, although in some cases this can lead to problems,
particularly when a conversion operator to another type that supports
operator[](int) exists (such as pointers). Say, for example, you have a
string class with a conversion operator to const char *

class String
{
public:
// yadda yadda yadda
char & operator[](size_t);
char operator[](size_t) const;

operator const char *() const;
};

void foo()
{
String s;
s[4]; // ambiguous call
}

s[4] wouldn't be ambiguous if String::operator[] accepted int instead of
size_t, because the literal 4 is int, which either has to be promoted to
size_t for String::operator[], or s has to be converted to const char* for
operator[](const char*, int). Now, if String::operator[] accepted int,
you'll never have this problem (not even if you pass it size_t).

I think it's best to leave the argument to operator[]s for array-like
indexing as ints (or perhaps even better: ptrdiff_t) rather than as other
integral types, as that's how the standard defines it's built-in types.

- Sylvester
Feb 12 '07 #6
Sylvester Hesp wrote:
>
"Kai-Uwe Bux" <jk********@gmx.netwrote in message
news:eq**********@murdoch.acc.Virginia.EDU...
>Jonas Huckestein wrote:
>>hello,

somehow i can't figure out, how to overload the [] operator for a
referenced object. if i have

class MyClass {

int operator[](int i) { return 1; };

You might want to consider using std::size_t instead of int as the
argument
type.

Yes you would think that, although in some cases this can lead to
problems, particularly when a conversion operator to another type that
supports operator[](int) exists (such as pointers). Say, for example, you
have a string class with a conversion operator to const char *

class String
{
public:
// yadda yadda yadda
char & operator[](size_t);
char operator[](size_t) const;

operator const char *() const;
};

void foo()
{
String s;
s[4]; // ambiguous call
}

s[4] wouldn't be ambiguous if String::operator[] accepted int instead of
size_t, because the literal 4 is int, which either has to be promoted to
size_t for String::operator[], or s has to be converted to const char* for
operator[](const char*, int). Now, if String::operator[] accepted int,
you'll never have this problem (not even if you pass it size_t).

I think it's best to leave the argument to operator[]s for array-like
indexing as ints (or perhaps even better: ptrdiff_t) rather than as other
integral types, as that's how the standard defines it's built-in types.
Well, I beg to differ. I agree that the example demonstrates a problem.
However, I would locate the problem in the example at a different position:
the conversion operator to char* should be made explicit, i.e., it should
be a member function like data() or c_str(). This is the precedent set by
the standard library. Generally, implicit conversions can lead to
surprises, and this is what your example demonstrates.

The standard library makes operator[] take size_type for container types and
difference_type for iterator types, which makes perfect sense. Note that
raw-pointers are more like iterators than containers. The class in you
example may suffer from not knowing what it wants to be. By and large, I
tend to follow the standard library in those questions. It makes my code
base more coherent.
Best

Kai-Uwe Bux
Feb 12 '07 #7

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

Similar topics

6
by: Equis Uno | last post by:
Hi there, I just figured out how to use __add__() to overload the "+" operator for objects of a class. According to googel queries, I see other functions available to me for overloading other...
2
by: Chris E. Yoon | last post by:
I just want to hear people's opinions on this subject. My application has lots and lots of short-lived objects that use dynamic allocation/deallocation. After implementing its functionality, I...
5
by: bsaucer | last post by:
I am creating a class with operator overloads. It makes references to another class I've created, but do not wish to modify. I try to overload an operator having arguments having the other class...
1
by: Piotre Ugrumov | last post by:
I'm following your help. I have written the overload of the operator <<. This overload work! :-) But I have some problem with the overload of the operator >>. I have written the overload of this...
1
by: Nimmi Srivastav | last post by:
There's a rather nondescript book called "Using Borland C++" by Lee and Mark Atkinson (Que Corporation) which presents an excellent discussion of overloaded new and delete operators. In fact there...
7
by: Sean | last post by:
Can someone help me see why the following "operator=" overloading doesn't work under g++? and the error message is copied here. I see no reason the compiler complain this. Thanks, $ g++...
17
by: Chris | last post by:
To me, this seems rather redundant. The compiler requires that if you overload the == operator, you must also overload the != operator. All I do for the != operator is something like this: ...
5
by: Suman | last post by:
Having had a look at the C++ FAQ, comp.lang.c++ & comp.std.c++ archives and Stroustrup's FAQs (particularly the following: <url:http://www.research.att.com/~bs/bs_faq2.html#overload-dot/>) I am...
14
by: Jess | last post by:
Hi, I read about operator overloading and have a question regarding "operator->()". If I have two classes like this: struct A{ void f(); }; struct B{
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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?
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...

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.