News:

This week IPhone 15 Pro winner is karn
You can be too a winner! Become the top poster of the week and win valuable prizes.  More details are You are not allowed to view links. Register or Login 

Main Menu

c++ arrays tips - Very large hole int the type system for arrays and inheritance

Started by ben2ong2, October 06, 2006, 05:55:09 PM

Previous topic - Next topic

0 Members and 2 Guests are viewing this topic.

ben2ong2

[ Example adapted from "C++ Gotchas", tutorial notes by Tom
  Cargill, page 44. ]


class B {
  public:
     int x;
};

class D : public B {
  public:
     int y;
};


void foo (B a[])  // Note argument type
{
    for (int i = 0; i < 6; i++)
        printf ("%d %d\n", i, a.x);
}


main ()
{
    D d[6];

    for (int i = 0; i< 6; i++)
        d.x = i;

    f(d);

    return 0;
}

The output of this program (on some implementation) is shown below.
Moral of the story is that inheritance and arrays do not work
together well (there is little type safety).

0 0
1 536871025
2 1
3 7455272
4 2
5 -613566757
You are not allowed to view links. Register or Login
You are not allowed to view links. Register or Login