2

Possible Duplicate:
Operator overloading

I was wonder how can I over load the Conditional operator in cpp?

int a,b,c;

  a=10;
  b=11;
  c = (a>b) ? a : b;

Is it possible?

Community
  • 1
  • 1
0x90
  • 39,472
  • 36
  • 165
  • 245

3 Answers3

7

You cannot overload the conditional operator.

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
6

Several operators cannot be overloaded. These operators take a name, rather than an object, as their right operand:

  • Direct member access (.)

  • Deference pointer to class member (.*)

  • Scope resolution (::)

  • Size of (sizeof)

The conditional operator (?:) also cannot be overloaded.

Additionally, the new typecast operators: static_cast<>, dynamic_cast<>, reinterpret_cast<>, and const_cast<>, and the # and ## preprocessor tokens cannot be overloaded.

http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=23

P M
  • 837
  • 1
  • 10
  • 17
  • 1
    I'm not sure I'd agree with the statement that the operators you can't overload "take a name, rather than an object, as their right operand". The operator `.*` takes an arbitrary expression as its right operand, and `->` (which you can overload) takes a name. The difference is slightly different: `::` is a compile time operator, controlling name lookup, so overloading it makes no sense; `sizeof` can be used in constant expressions, and `?:` would require some special syntax and additional rules. `.` and `.*` are simply arbitrary choices. – James Kanze Feb 24 '12 at 10:31
  • "new typecast operators"? What language are you talking about? They've always been in Standard C++... – rubenvb Feb 24 '12 at 12:21
  • I remember overloading unary left `*`, how's that different from what you denote as `.*`? – exebook Jun 24 '15 at 14:35
1

No, you can't overload the conditional operator, since it's simply shorthand for a simple if..else block.

You can however overload the operators used in the condition, but not for primitive types such as int, like you have in your example above.

AusCBloke
  • 18,014
  • 6
  • 40
  • 44
  • The conditional operator is actually not shorthand. `if...else` blocks switch between zero or more statements (full lines of code), whereas the conditional operator switches between two expressions. – Bronzdragon Mar 11 '20 at 14:01