+ Reply to Thread
Results 1 to 2 of 2

Thread: What is assignment operator in C++?

  1. #1
    Junior Member
    Join Date
    Feb 2012
    Posts
    49

    What is assignment operator in C++?

    Hi All,

    What is assignment operator in C++? How to overload it?

    Regards.

  2. #2
    Hi,

    Assignment operator is useful when you need to assign user defined object to another.

    When user do not implement his/her own assignment operator for a class, compiler synthesize its assignment operator.

    Sometime user has to write its own assignment operator for the class.

    Following example shows how to do this:

    Code:
    #define MAX_MESSAGE_SIZE 100
    
    class CAssignmentOperator
    {
    private:
    	//to make this conversation simple make copy constructor private.
    	CAssignmentOperator(const CAssignmentOperator&) ;
    
    	char *m_pData ;
    
    public:
    	CAssignmentOperator() : m_pData(NULL)
    	{
    	}
    
    	CAssignmentOperator(char *pNewData)
    	{
    		m_pData = new char[MAX_MESSAGE_SIZE + 1] ;
    		if (NULL != m_pData)
    		{
    			strncpy(m_pData, pNewData, MAX_MESSAGE_SIZE) ;
    		}
    	}
    
    	~CAssignmentOperator()
    	{
    		if (NULL != m_pData)
    		{
    			delete []m_pData ;
    			m_pData = NULL ;
    		}
    	}
    
    	CAssignmentOperator& operator =(const CAssignmentOperator& objAssignmentOperator)
    	{
    		//check for self assignment!
    		if (this != &objAssignmentOperator)
    		{
    			//copy the members from objAssignmentOperator object to "this" object.
    			//before copy, we need to be sure of memory leaks in case "this" object contains any pointer.
    
    			//copy should be safe!
    			if (NULL != objAssignmentOperator.m_pData)
    			{
    				char *pDataTemp = new char[MAX_MESSAGE_SIZE + 1] ;
    
    				if (NULL != pDataTemp)
    				{
    					strncpy(pDataTemp, objAssignmentOperator.m_pData, MAX_MESSAGE_SIZE) ;
    
    					delete [] m_pData ;
    					m_pData = NULL ;
    
    					m_pData = pDataTemp ;
    				}
    			}
    		}
    
    		return *this ;
    	}
    } ;
    
    void UseAssignmentoperator()
    {
    	CAssignmentOperator objAssignmentOperator1("Hello World!!!") ;
    	CAssignmentOperator objAssignmentOperator2 ;
    
    	//This is use of assignement operator!
    	objAssignmentOperator2 = objAssignmentOperator1 ;
    }
    Note:
    User will need to take care of self assignment case.

    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