+ Reply to Thread
Results 1 to 2 of 2

Thread: What is self assignment in C++?

  1. #1

    What is self assignment in C++?

    What is self assignment in C++?

    Any example will be of great help?

    Thanks.

  2. #2
    Senior Member
    Join Date
    Feb 2012
    Posts
    109
    Consider the following example:

    Code:
    #define MAX_MESSAGE_SIZE 100
    
    class CAssignmentOperator
    {
    private:
    	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)
    		{
    			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 assignment operator!
    	objAssignmentOperator2 = objAssignmentOperator1 ;
    }
    In assignment operator method it checks whether it does not assign to itself!

    I think it should clear answer your question.

+ Reply to 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