+ Reply to Thread
Results 1 to 2 of 2

Thread: What is diamond problem in C++?

  1. #1

    What is diamond problem in C++?

    What is diamond problem in C++? Please give me example of it?

    Thanks.

  2. #2
    Senior Member
    Join Date
    Feb 2012
    Posts
    109
    In multiple and multi-level inheritance, it is posible that most derived class can inherit multiple copies of the Most base class via multiple intermediated derived class of the Most base class!

    Below example shows that:

    Code:
    class CGrandParent
    {
    private:
    	int m_nGrandParent ;
    public:	
    	CGrandParent()
    	{
    		
    	}
    
    	int GetGrandParent()
    	{
    		return m_nGrandParent ;
    	}
    } ;
    
    
    class CParent1 : public CGrandParent //: public virtual CGrandParent
    {
    private:
    	int m_nParent1 ;
    public:	
    	CParent1()
    	{
    		
    	}
    } ;
    
    class CParent2 : public CGrandParent //: public virtual CGrandParent
    {
    private:
    	int m_nParent2 ;
    public:	
    	CParent2()
    	{
    		
    	}
    } ;
    
    class CGrandChild : public CParent1, public CParent2
    {
    public:
    	CGrandChild()
    	{
    	}
    } ;
    
    
    void DiamondProblem()
    {
    	CGrandChild objGrandChild ;
    
            //without 'virtual base class, following is the error,
            //error C2385: 'CGrandChild::GetGrandParent' is ambiguous
    	objGrandChild.GetGrandParent() ;
    }
    To resolve the error, use "public virtual CGrandParent" rather than "public CGrandParent"

    Hope this helps.

+ 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