Articles

What is operator overloading in C++?

What is operator overloading in C++?


In this C++ interview questions, we will learn about:

  • what is operator overloading in c++?

  • properties of operator overloading in c++
  • example of operator overloading in c++

What is Operator Overloading in C++?

Operator overloading is a type of polymorphism that gives C++ ability to the operator with preference to data type and have user-defined meaning to it.

 

Example: using '+' operator, two strings can be concatenated.

 

Properties of Operator Overloading

  • The overloaded operator has a return type and parameter list.
  • Operations happened over user-defined data types.
  • In this feature, C++ allows programmers to redefine the meaning of operator.

Syntax of operator overloading in c++

 

Return_type class :: operator

sign_of_operator(argument1, argument2,...)
{
//function definition
}

Operator Overloading can be done by implementing on this type of functions:

  • member/non-member functions and
  • friend function.

Example of operator overloading in c++

Operator overloading in c++ example is given below:

/* Program of operator overloading for Unary Minus operator */
#include <iostream> 
#include<conio.h>
using namespace std;  

class Un 
 {  
    unsigned int c;

   public:  
        Un()    
        {    
            c=0;    
        }    
        Un(int c1)   
        {    
            c=c1;    
        }  
        int counter()
        {
            return c;
        }
        void operator -()
        {
            c=-c;
        }
}; 
 
int main()   
{  
    Un c2(50),c3(100);
    cout<<"C1:"<<c2.counter()<<endl;
    cout<<"C2:"<<c3.counter()<<endl;
    -c3;
    cout<<"C1:"<<c2.counter()<<endl;
    cout<<"C2:"<<c3.counter()<<endl;
    return 0;  
}  

OUTPUT

C1:50

C2:100

C1:50

C2:-100

 

The operators that are not overloaded:

  • sizeof
  • scope resolution operator(::)
  • ternary operator(?:)

cpp interview questions

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Subhajit Guha Thakurta
Page Views :    Published Date : Feb 24,2021  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!