+ Reply to Thread
Results 1 to 3 of 3

Thread: What is Object slicing in C++?

  1. #1

    What is Object slicing in C++?

    What is Object slicing in C++?

    Please provide any example.

  2. #2
    Object slicing occurs when there is a class hierarchy.

    Derived class object can be sliced if proper implementation is not done.

    Following example shows how object slicing can occur and how to solve it.

    Example:

    Code:
    class CBase
    {
    protected:
    	int m_nValue1 ;
    public:
    	CBase()
    	{
    		m_nValue1 = 0 ;
    	}
    	
    	CBase(int nValue)
    	{
    		m_nValue1 = nValue ;
    	}
    
    	CBase(const CBase& objBase)
    	{
    		m_nValue1 = objBase.m_nValue1 ;
    	}
    
    	virtual void DisplayValue()
    	{
    		char szMessage[100] ;
    		sprintf(szMessage, "Value is = %d", m_nValue1) ;
    		OutputDebugString(szMessage) ;
    	}
    } ;
    
    class CDerived : public CBase
    {
    protected:
    	int m_nValue2 ;
    public:
    	CDerived(int nValue) : CBase(nValue)
    	{
    		m_nValue2 = 100 ;
    	}
    
    	CDerived(const CDerived& objDerived)
    	{
    		m_nValue2 = objDerived.m_nValue2 ;
    	}
    
    	virtual void DisplayValue()
    	{
    		char szMessage[100] ;
    		sprintf(szMessage, "Value is = %d", m_nValue2) ;
    		OutputDebugString(szMessage) ;
    	}
    } ;
    
    
    void IWillSliceYou(CBase objBase)
    {
    	//objBase is only a CBase object.
    	objBase.DisplayValue() ;
    	
    	//This cast should happen as per theory.
    	//But it returns NULL!
    	//This is because CDerived object is sliced here!
    	CDerived *pDerived = dynamic_cast<CDerived *> (&objBase) ;
    	if (NULL != pDerived)
    	{
    		pDerived->DisplayValue() ;
    	}
    }
    
    void IAmPerfect(CBase& objBase) //here, "&" pass by reference is important...
    {
    	//objBase is only a CBase object.
    	objBase.DisplayValue() ;
    	
    	//This will cast as per theory.
    	//Great!
    	CDerived *pDerived = dynamic_cast<CDerived *> (&objBase) ;
    	if (NULL != pDerived)
    	{
    		pDerived->DisplayValue() ;
    	}
    }
    
    void ObjectSlicing()
    {
    	CDerived objDerived(42) ;
    
    	objDerived.DisplayValue() ;
    
    	IWillSliceYou(objDerived) ;
    
    	IAmPerfect(objDerived) ;
    }

  3. #3
    Wow, great example. Thanks buddy.

+ 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