I could use some help understanding the following in C++, particularly the difference between an operator and a function:
What is an operator?
An operator is a symbol that is use in expressions.
Examples are: + - * / etc
On built-in types there operations are well defined and unchangable.
For user defined types the operators can be defined as syntactic sugar for a function/method call
Array a;
a = b + c; // a.operator=(b.operator+(c));
What is a function?
We use the term function/method interchangeably most of the time. The only difference is that a method is associated with an instance of a class object. Otherwise they are the same. They provide a way of grouping a set of instructions together.
What is the difference between them?
The action of an operator on a built-in type is defined by the compiler.
The action of an operator on a user defined type is a function call.
Is a user-defined operator+() a function or an operator?
Its a function (or a method). Use of an operator on a user defined type is syntactic sugar for a function call. They are still refereed to as operators though in normal conversation.
Can an operator operate on operands at compile-time?
For built-in types yes. The compiler has extensive ability to optimize there usage.
For user defined types. It can perform optimizations on the operators just like other functions which may lead to there being eliminated, but the code is not executed at compile time.
Do they always operate at compile time? (like sizeof() in C++)
No. sizeof() is relatively unique.
To show that operator in user defined class behave just like functions here is an example of using mem_fun_ref
#include
#include
#include
#include
class X
{
public:
// Non standard operators.
// Because std::mem_fun_ref has a known weakness in that it can
// not be used with methods that take parameters be reference.
//
// The principle is the same though. That the operator+ can be
// used anywhere that the add() method can be used.
X& operator+(X* rhs) { return *this;}
X& add(X* rhs) { return *this;}
};
typedef X& (X::*MEMF)(X* rhs);
int main()
{
MEMF p1 = &X::add;
MEMF p2 = &X::operator+;
X value;
std::vector data;
std::for_each(data.begin(),
data.end(),
std::bind2nd(std::mem_fun_ref(&X::operator+),&value));
}