+ Reply to Thread
Results 1 to 2 of 2

Thread: Why below code does not print the expected output using inheritance?

  1. #1

    Why below code does not print the expected output using inheritance?

    Why below code does not print the expected output using inheritance?

    Code:
    class CBase
    {
    public:
    	int a;
    	CBase()
    	{
    		a = 100 ;
    	}
    } ;
    
    class CDerive : public CBase
    {
    public:
    	int b, c ;
    	CDerive()
    	{
    		b = 200 ;
    		c = 300 ;
    	}
    } ;
    
    
    void UseBase(CBase obj[3])
    {
        for (int nIndex=0; nIndex<3; nIndex++)
    	{
            char szMessage[100] ;
    		sprintf(szMessage, "%d %d\n", nIndex, obj[nIndex].a) ;
    		OutputDebugString(szMessage) ;
    	}
    }
    
    void UseArrayInheritance()
    {
    	CDerive objDerive[3] ;
    
        UseBase(objDerive) ;
    }
    Am I missing something or it is C++/compiler specific issue?

    Please help and guide me.

  2. #2
    Array with inheritance are evil. You should avoid this.

    In above example, compiler thinks that it should get the next object by incrementing sizeof(CBase) class and that is not desirable result for you.

    So it will print the result as 100, 200 and 300 where size of CBase is 4 bytes (size of int).

    Note that I have compile the above example using VC++ 6.0.

+ 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