Sunday, 22 March 2015

What are the Operators we can’t overload in C++

What are the Operators we can’t overload in Cpp with examples:

There are some operator that we cannot be overloaded.
The list is below
(Member Access or Dot operator)

?: (Ternary or Conditional Operator )

:: (Scope Resolution Operator)

.* (Pointer-to-member Operator )

sizeof(Object size Operator)

typeid (Object type Operator) 

There is no fundamental reason to disallow overloading of ?:.

Note: Suppose a function overloading expr1?expr2:expr3 would not be able to guarantee that only one of expr2 and expr3 was executed.

The Sizeof cannot be overloaded because built-in operations,See the below  code snippet
  Type oca[10];

 Type * pcp = &oca[3];

 Type * pcq = &oca[3];

 pcp++; // pcp points to a[4]

  // thus the integer value of p must be

  // sizeof(Type) larger than the integer value of q

Thus, sizeof(Type) could not be given a new and different meaning by the programmer without violating basic language rules.

In N::m neither N nor m are expressions with values; N and m are names known to the compiler and :: performs a (compile time) scope resolution rather than an expression evaluation. One could imagine allowing overloading of x::y where Type is an object rather than a namespace or a class, but that would - contrary to first appearances - involve introducing new syntax (to allow expr::expr). It is not obvious what benefits such a complication would bring.

Operator . (dot) could in principle be overloaded using the same technique as used for ->. However, doing so can lead to questions about whether an operation is meant for the object overloading . or an object referred to by . See another code snippet
 class Test {


  void fun();

  // ...

 class Test1 { // assume that you can overload .
     Test* pcObj;
   Test& operator.() { return *pcObj; }
   void fun ();
 void Fun2 (Type1& ocType)
   ocType. fun (); // Type1::fun or Type::fun or error?

No comments: