+ Reply to Thread
Results 1 to 2 of 2

Thread: What is operator overloading in C++?

  1. #1

    What is operator overloading in C++?

    Hi All,

    What is operator overloading in C++?

    Regards.

  2. #2
    Hi,

    User can overload an operator like (+, -, ++, --) as like overloading a method of a class.

    There are two types of operator overloading
    a. Unary
    b. Binary

    Example of Unary operator overloading:

    Code:
    class CIncrementer
    {
    private:
    	int m_nValue ;
    public:
    	CIncrementer()
    	{
    		m_nValue = 0 ;
    	}
    
    	CIncrementer(int nValue)
    	{
    		m_nValue = nValue ;
    	}
    
    	CIncrementer operator ++() //prefix
    	{
    		return CIncrementer(++m_nValue) ;
    	}
    
    	CIncrementer operator ++(int ) //postfix
    	{
    		return CIncrementer(++m_nValue) ;
    	}
    
    	int GetCurrentValue()
    	{
    		return m_nValue ;
    	}
    } ;
    
    void UseUnaryOpeartorOverloading()
    {
    	CIncrementer objIncrementer ;
    	int nCurrentValue = objIncrementer.GetCurrentValue() ;
    
    	objIncrementer++ ;
    	nCurrentValue = objIncrementer.GetCurrentValue() ;
    
    	++objIncrementer ;
    	nCurrentValue = objIncrementer.GetCurrentValue() ;
    }
    Example of Binary operator overloading:

    Code:
    class CComplex
    {
    private:
    	double m_dReal ;
    	double m_dImag ;
    
    public:
    	CComplex(double dReal, double dImag)
    	{
    		m_dReal = dReal ;
    		m_dImag = dImag ;
    	}
    
    	CComplex operator +(const CComplex& objComplex)
    	{
    		return CComplex(m_dReal + objComplex.m_dReal, m_dImag + objComplex.m_dImag) ;
    	}
    } ;
    
    void UseBinaryOpeartorOverloading()
    {
    	CComplex objComplex1(10.0, 20.0) ;
    
    	CComplex objComplex2(30.0, 40.0) ;
    
    	CComplex objComplex3 = objComplex1 + objComplex2 ;
    }
    Note:
    a. Almost all the operator can be overloaded in C++.
    b. List of operators that cannot be overloaded is: ".", ".*", "::"
    c. It is assumed that you follow the general rule when overload an operator for a class. That is when you overload "+" operator, client is assuming that you are performing addition not subtraction within the class.

    Regards.

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts