pointer arthrmetic using operator overloading?

B

Bharath

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
 
T

Thomas J. Gritzan

Bharath said:
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.
 
R

Rolf Magnus

Bharath said:
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.
 

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,787
Messages
2,569,631
Members
45,338
Latest member
41Pearline46

Latest Threads

Top