By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,797 Members | 1,794 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,797 IT Pros & Developers. It's quick & easy.

pointer arthrmetic using operator overloading?

P: n/a
Hello All,
Can you please let me know if we can do pointer arthrmetic using
operator overloading? If not, can you please explain why it's not
supported by compiler?

I tried below e.g. which was giving me error.

typedef class x
{
}X;
void operator +(X *p,X *q)
{
}
main()
{
X *p,*q;
p+q;
}

[/home/dbk/temp_eg]: gcc ptr.cpp
ptr.cpp:5: `operator +(X *, X *)' must have an argument of class or
enumerated type
ptr.cpp: In function `int main()':
ptr.cpp:10: invalid operands `X *' and `X *' to binary `operator +'
Any idea what are these errors?

TIA,
Bharath

Jun 12 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Bharath wrote:
Hello All,
Can you please let me know if we can do pointer arthrmetic using
operator overloading? If not, can you please explain why it's not
supported by compiler?
You can only overload operators for user defined types (i.e. classes).
Pointers are predefined types.

--
Thomas
http://www.netmeister.org/news/learn2quote.html
Jun 12 '07 #2

P: n/a
Bharath wrote:
Hello All,
Can you please let me know if we can do pointer arthrmetic using
operator overloading?
Yes. However, you cannot replace the built-in functionality for pointers
with a user-defined operator.
If not, can you please explain why it's not supported by compiler?
The idea of operator overloading is that you can extend the language, not
replace the existing functionality with different behavior. So you cannot
write yur own operators for built-in types, but only for user-defined ones.
I tried below e.g. which was giving me error.

typedef class x
{
}X;
void operator +(X *p,X *q)
{
}
main()
{
X *p,*q;
p+q;
}

[/home/dbk/temp_eg]: gcc ptr.cpp
ptr.cpp:5: `operator +(X *, X *)' must have an argument of class or
enumerated type
An operator must have at least one argument of user-defined type, and
pointers are built-in types.
ptr.cpp: In function `int main()':
ptr.cpp:10: invalid operands `X *' and `X *' to binary `operator +'
The compiler didn't accept your definition of operator +, so none is defined
at this point.

Btw: an operator+ that returns void is quite strange.

Jun 12 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.