The Wayback Machine - https://web.archive.org/web/20240906013818/https://www.geeksforgeeks.org/what-are-the-operators-that-can-be-and-cannot-be-overloaded-in-cpp/
Open In App

What are the Operators that Can be and Cannot be Overloaded in C++?

Last Updated : 27 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

There are various ways to overload Operators in C++ by implementing any of the following types of functions:

1) Member Function

2) Non-Member Function

3) Friend Function

List of operators that can be overloaded are: 

+

–

 *

?

%

?

 &

|

 ~

!

=

 <

>

+=

-=

 *=

?=

%=

?=

&=

|=

 <<

 >>

<<=

>>=

==

 !=

<=

>=

&&

||

 ++

 —

,

->*

->

( )

[ ]

new

delete

new[]

delete[]

 

   

Example 1: Overloading ++ Operator 

CPP




// CPP program to illustrate
// operators that can be overloaded
#include <iostream>
using namespace std;
 
class overload {
private:
    int count;
 
public:
    overload()
        : count(4)
    {
    }
 
    void operator++() { count = count + 1; }
    void Display() { cout << "Count: " << count; }
};
 
int main()
{
    overload i;
    // this calls "function void operator ++()" function
    ++i;
    i.Display();
    return 0;
}


Output

Count: 5

This function is called when the ++ operator operates on the object of the overload class (object i in this case). In the program, void operator ++ () operator function is defined (inside overload class). This function increments the value of count by 1 for i object.
Example 2: Overloading ++ operator i.e. pre and post increment operator 

CPP




// CPP program to demonstrate the
// Difference between pre increment
// and post increment overload operator
#include <iostream>
using namespace std;
 
class overload {
private:
    int count;
 
public:
    overload(int i)
        : count(i)
    {
    }
 
    overload operator++(int) { return (count++); }
    overload operator++()
    {
        count = count + 1;
        return count;
    }
    void Display() { cout << "Count: " << count << endl; }
};
// Driver code
int main()
{
    overload i(5);
    overload post(5);
    overload pre(5);
 
    // this calls "function overload operator ++()" function
    pre = ++i;
    cout << "results of I   =   ";
    i.Display();
    cout << "results of preincrement   =  ";
    pre.Display();
    // this call "function overload operator ++()"function
    i++; // just to show diff
    i++; // just to show diff
    post = i++;
    cout << "Results of post increment   =   ";
    post.Display();
    cout << "And results of i , here we see difference   : "
            "  ";
    i.Display();
    return 0;
}


Output

results of I   =   Count: 6
results of preincrement   =  Count: 6
Results of post increment   =   Count: 8
And results of i , here we see difference   :   Count: 9

Example 3: Overloading [ ] operator 

CPP




// CPP program to illustrate overloading the
// [ ] operator
 
#include <iostream>
using namespace std;
class overload {
    int a[3];
 
public:
    overload(int i, int j, int k)
    {
        a[0] = i;
        a[1] = j;
        a[2] = k;
    }
    int operator[](int i) { return a[i]; }
};
int main()
{
    overload ob(1, 2, 3);
    cout << ob[1]; // displays 2
    return (0);
}


Output

2

Example 4 : Overloading -> operator 

CPP




// CPP program to illustrate
// operators that can be overloaded
#include <bits/stdc++.h>
using namespace std;
 
class GFG {
public:
    int num;
    GFG(int j) { num = j; }
    GFG* operator->(void) { return this; }
};
 
// Driver code
int main()
{
    GFG T(5);
    GFG* Ptr = &T;
 
    // Accessing num normally
    cout << "T.num = " << T.num << endl;
 
    // Accessing num using normal object pointer
    cout << "Ptr->num = " << Ptr->num << endl;
 
    // Accessing num using -> operator
    cout << "T->num = " << T->num << endl;
 
    return 0;
}


Output

T.num = 5
Ptr->num = 5
T->num = 5

List of operators that cannot be overloaded

1) Scope Resolution Operator  (::)    

2) Ternary or Conditional Operator (?:)   

3) Member Access or Dot operator  (.)    

4) Pointer-to-member Operator (.*)  

5) Object size Operator (sizeof) 

6) Object type Operator(typeid) 

7) static_cast (casting operator)

8) const_cast (casting operator)

9) reinterpret_cast (casting operator)

10) dynamic_cast (casting operator)

Example 5: Overloading this .(dot) operator
Dot (.) operator can’t be overloaded, so it will generate an error. 

CPP




// C++ program to illustrate
// Overloading this .(dot) operator
#include <iostream>
using namespace std;
 
class cantover {
public:
    void fun();
};
class X {
    cantover* p;
    cantover& operator.() { return *p; }
    void fun();
};
void g(X& x)
{
    x.fun(); // X::fun or cantover::fun or error?
}


Output: Error

prog.cpp:12:23: error: expected type-specifier before ‘.’ token
    cantover& operator.() { return *p; }

This program will generate an error. Similarly, the above operators will also generate an error, if overloaded.



Previous Article
Next Article

Similar Reads

Functions that cannot be overloaded in C++
In C++, following function declarations cannot be overloaded. 1) Function declarations that differ only in the return type. For example, the following program fails in compilation. C/C++ Code #include&amp;lt;iostream&amp;gt; int foo() { return 10; } char foo() { return 'a'; } int main() { char x = foo(); getchar(); return 0; } 2) Member function de
3 min read
Can main() be overloaded in C++?
Predict the output of following C++ program. #include &lt;iostream&gt; using namespace std; int main(int a) { cout &lt;&lt; a &lt;&lt; &quot;\n&quot;; return 0; } int main(char *a) { cout &lt;&lt; a &lt;&lt; endl; return 0; } int main(int a, int b) { cout &lt;&lt; a &lt;&lt; &quot; &quot; &lt;&lt; b; return 0; } int main() { main(3); main(&quot;C++
2 min read
error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++
Pre-requisite: Function Overloading in C++ Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. Two or more functions are said to be overloaded if they differ in any of th
9 min read
Hiding of all Overloaded Methods with Same Name in Base Class in C++
In C++, function overloading is possible i.e., two or more functions from the same class can have the same name but different parameters. However, if a derived class redefines the base class member method then all the base class methods with the same name become hidden in the derived class. For example, the following program doesn't compile. Here,
3 min read
How to Specify a Pointer to an Overloaded Function?
In C++, function overloading allows multiple functions to have the same name but different parameter lists. While overloading is a powerful feature, it can lead to ambiguity when trying to assign a pointer to one of these overloaded functions. To resolve this ambiguity, specific methods can be used to correctly specify a pointer to the desired over
4 min read
What are the differences between bitwise and logical AND operators in C/C++?
A Bitwise And operator is represented as '&amp;' and a logical operator is represented as '&amp;&amp;'. The following are some basic differences between the two operators. a) The logical and operator '&amp;&amp;' expects its operands to be boolean expressions (either 1 or 0) and returns a boolean value. The bitwise and operator '&amp;' work on Inte
4 min read
Increment and Decrement Operators in C
The increment ( ++ ) and decrement ( -- ) operators in C are unary operators for incrementing and decrementing the numeric values by 1 respectively. The incrementation and decrementation are one of the most frequently used operations in programming for looping, array traversal, pointer arithmetic, and many more. In this article, we will discuss the
4 min read
C++ Increment and Decrement Operators
Prerequisite: Operators in C++ What is a C++ increment Operator? The C++ increment operator is a unary operator. The symbol used to represent the increment operator is (++). The increment operator increases the value stored by the variable by 1. This operator is used for Numeric values only. There are two types of C++ increment Operator: Pre-Increm
4 min read
G-Fact 19 (Logical and Bitwise Not Operators on Boolean)
Most of the languages including C, C++, Java, and Python provide a boolean type that can be either set to False or True. In this article, we will see about logical and bitwise not operators on boolean. Logical Not (or !) Operator in PythonIn Python, the logical not operator is used to invert the truth value of a Boolean expression, returning True i
4 min read
Conditionally assign a value without using conditional and arithmetic operators
Given 4 integers a, b, y, and x, where x can assume the values of either 0 or 1 only. The following question is asked: If 'x' is 0, Assign value 'a' to variable 'y' Else (If 'x' is 1) Assign value 'b' to variable 'y'. Note: - You are not allowed to use any conditional operator (including the ternary operator) or any arithmetic operator (+, -, *, /)
6 min read
new and delete Operators in C++ For Dynamic Memory
Dynamic memory allocation in C/C++ refers to performing memory allocation manually by a programmer. Dynamically allocated memory is allocated on Heap, and non-static and local variables get memory allocated on Stack (Refer to Memory Layout C Programs for details). What are applications?  One use of dynamically allocated memory is to allocate memory
6 min read
Left Shift and Right Shift Operators in C/C++
In C/C++, left shift (&lt;&lt;) and right shift (&gt;&gt;) operators are binary bitwise operators that are used to shift the bits either left or right of the first operand by the number of positions specified by the second operand allowing efficient data manipulation. In this article, we will learn about the left shift and right shift operators. Le
6 min read
# and ## Operators in C
Stringizing operator (#)The stringizing operator (#) is a preprocessor operator that causes the corresponding actual argument to be enclosed in double quotation marks. The # operator, which is generally called the stringize operator, turns the argument it precedes into a quoted string. It is also known as the stringification operator. It is general
2 min read
Arithmetic Operators in C
Arithmetic Operators are the type of operators in C that are used to perform mathematical operations in a C program. They can be used in programs to define expressions and mathematical formulas. What are C Arithmetic Operators? The C arithmetic operators are the symbols that are used to perform mathematical operations on operands. There are a total
7 min read
C | Operators | Question 2
#include &lt;stdio.h&gt; int main() {     int i = 1, 2, 3;          printf("%d", i);          return 0; } (A) 1 (B) 3 (C) Garbage value (D) Compile time error Answer: (D) Explanation: Comma acts as a separator here. The compiler creates an integer variable and initializes it with 1. The compiler fails to create integer variable 2 because 2 is not a
1 min read
C | Operators | Question 3
#include &lt;stdio.h&gt; int main() {     int i = (1, 2, 3);          printf("%d", i);          return 0; } (A) 1 (B) 3 (C) Garbage value (D) Compile time error Answer: (B) Explanation: The bracket operator has higher precedence than assignment operator. The expression within bracket operator is evaluated from left to right but it is always the res
1 min read
C | Operators | Question 4
#include &lt;stdio.h&gt; int main() {     int i;        i = 1, 2, 3;     printf("%d", i);          return 0; } (A) 1 (B) 3 (C) Garbage value (D) Compile time error Answer: (A) Explanation: Comma acts as an operator. The assignment operator has higher precedence than comma operator. So, the expression is considered as (i = 1), 2, 3 and 1 gets assign
1 min read
C | Operators | Question 5
C/C++ Code #include int main() { int i = 3; printf(\"%d\", (++i)++); return 0; } What is the output of the above program? (A)3 (B)4 (C)5 (D)Compile-time error Answer: (D)Explanation: In C, prefix and postfix operators need l-value to perform operation and return r-value. The expression (++i)++ when executed increments the value of variable i(i is a
1 min read
C | Operators | Question 6
What is the output of below program? #include &lt;stdio.h&gt; int foo(int* a, int* b) { int sum = *a + *b; *b = *a; return *a = sum - *b; } int main() { int i = 0, j = 1, k = 2, l; l = i++ || foo(&amp;j, &amp;k); printf(&quot;%d %d %d %d&quot;, i, j, k, l); return 0; } (A) 1 2 1 1 (B) 1 1 2 1 (C) 1 2 2 1 (D) 1 2 2 2 Answer: (A) Explanation: The con
1 min read
C | Operators | Question 7
#include &amp;lt;stdio.h&amp;gt; int main() { int i = 5, j = 10, k = 15; printf(&amp;quot;%d &amp;quot;, sizeof(k /= i + j)); printf(&amp;quot;%d&amp;quot;, k); return 0; } Assume size of an integer as 4 bytes. What is the output of above program? (A) 4 1 (B) 4 15 (C) 2 1 (D) Compile-time error Answer: (B) Explanation: The main theme of the program
1 min read
C | Operators | Question 8
#include &lt;stdio.h&gt; int main() { //Assume sizeof character is 1 byte and sizeof integer is 4 bytes printf(&quot;%d&quot;, sizeof(printf(&quot;GeeksQuiz&quot;))); return 0; } (A) GeeksQuiz4 (B) 4GeeksQuiz (C) GeeksQuiz9 (D) 4 (E) Compile-time error Answer: (D) Explanation: An expression doesn't get evaluated inside sizeof operator. GeeksQuiz wi
1 min read
C | Operators | Question 9
Output of following program? #include &lt;stdio.h&gt; int f1() { printf (&quot;Geeks&quot;); return 1;} int f2() { printf (&quot;Quiz&quot;); return 1;} int main() { int p = f1() + f2(); return 0; } (A) GeeksQuiz (B) QuizGeeks (C) Compiler Dependent (D) Compiler Error Answer: (C) Explanation: The operator ‘+’ doesn't have a standard defined order o
1 min read
C | Operators | Question 13
C/C++ Code #include int main(void) { int a = 1; int b = 0; b = a++ + a++; printf(\"%d %d\",a,b); return 0; } (A) 3 6 (B) Compiler Dependent (C) 3 4 (D) 3 3 Answer: (B) Explanation: It is compiler dependent as different compilers takes different bytes for integers. Quiz of this Question Please comment below if you find anything wrong in the above po
1 min read
C | Operators | Question 27
Which of the following is not a logical operator? (A)&amp;&amp; (B)! (C)|| (D)| Answer: (D)Explanation: &amp;&amp;- Logical AND !- Logical NOT ||- Logical OR |- Bitwise OR(used in bitwise manipulations) Quiz of this QuestionPlease comment below if you find anything wrong in the above post
1 min read
C | Operators | Question 15
Predict the output of following program. Assume that the characters are represented using ASCII Values. #include &lt;stdio.h&gt; #define VAL 32 int main() { char arr[] = &quot;geeksquiz&quot;; *(arr + 0) &amp;= ~VAL; *(arr + 5) &amp;= ~VAL; printf(&quot;%s&quot;, arr); return 0; } (A) GeeksQuiz (B) geeksQuiz (C) Geeksquiz (D) geeksquiz (E) Garbage
1 min read
C | Operators | Question 16
Predict the output of the below program: #include &lt;stdio.h&gt; int main() { printf(&quot;%d&quot;, 1 &lt;&lt; 2 + 3 &lt;&lt; 4); return 0; } (A) 112 (B) 52 (C) 512 (D) 0 Answer: (C) Explanation: The main logic behind the program is the precedence and associativity of the operators. The addition(+) operator has higher precedence than shift(&lt;
1 min read
C | Operators | Question 17
Which of the following can have different meaning in different contexts? (A) &amp; (B) * (C) Both of the above (D) There are no such operators in C Answer: (C) Explanation: '&amp;' can be used to get address of a variable and can also be used to do bitwise and operation. Similarly '*' can be used to get value at an address and can also be used to m
1 min read
C | Operators | Question 26
What does the following statement do? x = x | 1 &lt;&lt; n; (A) Sets x as 2n (B) Sets (n+1)th bit of x (C) Toggles (n+1)th bit of x (D) Unsets (n+1)th bit of x Answer: (B) Explanation: Let n be 3, the value of expression 1 &lt;&lt; n would be 8 (In binary 00001000). If we do bitwise or of binary 00001000 with any number x would set its (n+1)th bit
1 min read
C | Operators | Question 27
Predict the output of following C program C/C++ Code #include int main() { int i = 0; do { printf(\"GeeqsQuiz \"); i = i++; } while (i (A) GeeqsQuiz GeeqsQuiz GeeqsQuiz GeeqsQuiz GeeqsQuiz (B) Infinite time GeeksQuiz (C) Undefined Behavior (D) None of the above Answer: (C) Explanation: The below statement causes undefined behavior. i = i++; Quiz of
1 min read
C | Operators | Question 21
Assume that the size of an integer is 4 bytes, predict the output of following program. #include &lt;stdio.h&gt; int main() { int i = 12; int j = sizeof(i++); printf(&quot;%d %d&quot;, i, j); return 0; } (A) 12 4 (B) 13 4 (C) Compiler Error (D) 0 4 Answer: (A) Explanation: The expressions written inside sizeof are not evaluated, so i++ is not perfo
1 min read
Practice Tags :