Leif Andersen
Leif Andersen

Reputation: 22342

Operator Overloading in C

In C++, I can change the operator on a specific class by doing something like this:

MyClass::operator==/*Or some other operator such as =, >, etc.*/(Const MyClass rhs) {
    /* Do Stuff*/;
}

But with there being no classes (built in by default) in C. So, how could I do operator overloading for just general functions?

For example, if I remember correctly, importing stdlib.h gives you the -> operator, which is just syntactic sugar for (*strcut_name).struct_element.

So how can I do this in C?

Thank you.

Upvotes: 7

Views: 2808

Answers (4)

user290149
user290149

Reputation: 109

Sure, you can't overload operators in C. The -> operator is part of the C language, no #include needed.

Upvotes: 1

AnT stands with Russia
AnT stands with Russia

Reputation: 320631

Built-in operators in C language are overloaded. The fact that you can use binary + to sum integers, floating-point numbers and perform pointer arithmetic is a canonical example of operator overloading.

However, C offers no features for user-level operator overloading. You can't define your own operators in C.

Upvotes: 5

spoulson
spoulson

Reputation: 21591

The -> structure pointer dereferencing operator is part of the C spec. stdlib.h does not affect this.

Upvotes: 1

Mark Rushakoff
Mark Rushakoff

Reputation: 258358

Plain old C does not have operator overloading in any form. The -> "operator" to access a member of a pointer is standard C and is not introduced by any header file.

Upvotes: 15

Related Questions