Output needs some explanation

Discussion in 'C' started by shabbir, Jul 19, 2005.

  1. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    Can any one give any valid reason why the output of the following program in VC++ 6.0 Compiler is
    Code:
    #include <iostream>
    using namespace std;
    
    class base
    {
    public:
      int a;
      base(){ a=0;}
    };
    
    class der:public base
    {
    public:
      int b;
      der(){ b=1;}
    };
    void F(base *ptr,int n)
    {
      for(int i=0; i<n; i++,ptr++)
        cout<<ptr->a;
      cout<<endl;
    }
    
    int main()
    {
      base Base1[5];
      F(Base1,5);
      der Der1[5];
      F(Der1,5);
      return 0;
    }
    Output
    00000
    01010
     
  2. coderzone

    coderzone Super Moderator

    Joined:
    Jul 25, 2004
    Messages:
    736
    Likes Received:
    38
    Trophy Points:
    28
    Hey very interesting problem. I will try this.
     
  3. coderzone

    coderzone Super Moderator

    Joined:
    Jul 25, 2004
    Messages:
    736
    Likes Received:
    38
    Trophy Points:
    28
    The catch lies here

    for(int i=0; i<n; i++,ptr++)

    If you see there is a ptr ++ and ptr is always a base pointer and so the amount of values that are incremented at\re size of base and so once it prints a and then b and so the output is 01010
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice