+ Reply to Thread
Results 1 to 2 of 2

Thread: What is copy constructor?

  1. #1

    What is copy constructor?

    Hi All,

    What is copy constructor in C++?

    Regards.

  2. #2
    Senior Member
    Join Date
    Feb 2012
    Posts
    109
    Hi,

    Copy constructor is a special function of a class.

    By default if user do not supply copy constructor then compiler synthesize its own copy constructor. This has limited usage.

    In many cases user will need to supply its own copy constructor.

    Following example shows usage of copy constructor.

    Code:
    class CCopyConstructor
    {
    	char *m_pData ;
    
    public:
    	CCopyConstructor() : m_pData(NULL)
    	{
    	}
    
    	CCopyConstructor(char *pNewData)
    	{
    		if (NULL != pNewData)
    		{
    			m_pData = new char[MAX_MESSAGE_SIZE + 1] ;
    			if (NULL != m_pData)
    			{
    				strncpy(m_pData, pNewData, MAX_MESSAGE_SIZE) ;
    			}
    		}
    	}
    
    	~CCopyConstructor()
    	{
    		if (NULL != m_pData)
    		{
    			delete []m_pData ;
    			m_pData = NULL ;
    		}
    	}
    
    	CCopyConstructor(const CCopyConstructor& objCopyConstructor)
    	{
    		if (NULL != objCopyConstructor.m_pData)
    		{
    			m_pData = new char[MAX_MESSAGE_SIZE + 1] ;
    
    			if (NULL != m_pData)
    			{
    				strncpy(m_pData, objCopyConstructor.m_pData, MAX_MESSAGE_SIZE) ;
    			}
    		}
    	}
    
    	char* GetData()
    	{
    		return m_pData ;
    	}
    } ;
    
    void UseCopyConstructor()
    {
    	CCopyConstructor objCopyConstructor1("Hello World!!!") ;
    
           //This will execute copy constructor.
    	CCopyConstructor objCopyConstructor2(objCopyConstructor1) ;
    }
    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