By Satavisa Das
C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. Operator overloading is a compile-time polymorphism.
The above image is an example of operator overloading in C++.Here, the output will be 12+i9.
We can overload
- Unary operators
- Binary operators
- Special operators ( [ ], (), etc)
But, among them, there are some operators that cannot be overloaded. They are
- Scope resolution operator (:
- Member selection operator
- Member selection through *
Pointer to a member variable
Operators that can be overloaded | Examples |
---|---|
Binary Arithmetic | +, -, *, /, % |
Unary Arithmetic | +, -, ++, — |
Assignment | =, +=,*=, /=,-=, %= |
Bitwise | & , | , << , >> , ~ , ^ |
De-referencing | (->) |
Dynamic memory allocation, De-allocation |
New, delete |
Subscript | [ ] |
Function call | () |
Logical | &, | |, ! |
Relational | >, < , = =, <=, >= |
This returns the size of the object or datatype entered as the operand. This is evaluated by the compiler and cannot be evaluated during runtime. The proper incrementing of a pointer in an array of objects relies on the sizeof operator implicitly. Altering its meaning using overloading would cause a fundamental part of the language to collapse.
This provides a CPP program with the ability to recover the actually derived type of the object referred to by a pointer or reference. For this operator, the whole point is to uniquely identify a type. If we want to make a user-defined type ‘look’ like another type, polymorphism can be used but the meaning of the typeid operator must remain unaltered, or else serious issues could arise.
This helps identify and specify the context to which an identifier refers by specifying a namespace. It is completely evaluated at runtime and works on names rather than values. The operands of scope resolution are note expressions with data types and CPP has no syntax for capturing them if it were overloaded. So it is syntactically impossible to overload this operator.
1) For operator overloading to work, at least one of the operands must be a user-defined class object.
2) Assignment Operator: Compiler automatically creates a default assignment operator with every class. The default assignment operator does assign all members of the right side to the left side and works fine in most cases (this behavior is the same as the copy constructor).
3) Conversion Operator: We can also write conversion operators that can be used to convert one type to another type.
4) Any constructor that can be called with a single argument works as a conversion constructor, which means it can also be used for implicit conversion to the class being constructed.
Submitted by Satavisa Das (Satavisa)
Download packets of source code on Coders Packet
Comments