Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operators vs Functions in C/C++

Tags:

c++

Someone recently asked me the difference between a C++ standard operator (e.g. new,delete,sizeof) and function (e.g. tan,free, malloc). By "standard" I mean those provided by default by the compiler suite, and not user defined. Below were the answers I gave, though neither seemed satisfactory.

(1) An operator doesn't need any headers to be included to use it : E.g. you can have a call to new without including any headers. However, a function (say free() ) does need headers included, compulsorily.

(2) An operator is defined as such (ie as a class operator) somewhere in the standard headers. A function isn't.

Can you critique these answers and give me a better idea of the difference?

like image 396
PKG Avatar asked Jun 02 '10 06:06

PKG


1 Answers

Operators are keywords with a fixed syntax. Those which can be overloaded might vary a bit in syntax, but that's within the boundaries. The new operator is still spelled new, even when overloaded and the syntax of invoking it is always the same.

Function names are identifiers, which can be almost arbitrary. There's no syntactic reason you couldn't do away with malloc() and use

bool my_fancy_alloc(void*& memory, unsigned char size, bool zero_it);

instead. (Mark: There are other reasons, though. Like your fellow-workers' sanity.)

like image 90
sbi Avatar answered Oct 02 '22 14:10

sbi