Difference between operator and function in C++?

Nawaz picture Nawaz · Jan 16, 2011 · Viewed 11.8k times · Source

I could use some help understanding the following in C++, particularly the difference between an operator and a function:

  • What is an operator?
  • What is a function?
  • What is the difference between them?
  • Is a user-defined operator+() a function or an operator?
  • Can an operator operate on operands at compile-time? Do they always operate at compile time? (like sizeof() in C++)

Answer

Johannes Schaub - litb picture Johannes Schaub - litb · Jan 17, 2011

An operator is a symbol like +, -, += and so forth (see 13.5). They don't carry a meaning. During semantic analysis, the meaning of an operator is determined.

A function is a constructor, destructor, conversion function (that looks like operator type()) or operator function (function template specialization and instantiation can yield these in turn).

An operator function is something that implements an operator (see 13.5). An example is operator+. These are functions in all respects, and the only difference to "usual" functions is that they may be called implicitly and they have a funny name.

Some operators have a built-in meaning, that can be changed by the programmer. One refers to the built-in meaning of an operator simply by saying built-in operator (see 5/3). However, if such an operator is applied on operands for which a built-in meaning is defined, changing that meaning is only allowed for a few cases (these are assignment, address-of and the comma operator, see 13.5/6).