C++ new[] into base class pointer crash on array access

前端 未结 5 738
南笙
南笙 2020-12-21 10:24

When I allocate a single object, this code works fine. When I try to add array syntax, it segfaults. Why is this? My goal here is to hide from the outside world the fact

5条回答
  •  失恋的感觉
    2020-12-21 11:23

    You have an array of type "b" not of type "a" and you are assigning it to a pointer of type a. Polymorphism doesn't transfer to dynamic arrays.

     a* s
    

    to a

     b* s
    

    and you will see this start working.

    Only not-yet-bound pointers can be treated polymorphically. Think about it

     a* s = new B(); // works
     //a* is a holder for an address
    
     a* s = new B[10]
     //a* is a holder for an address
     //at that address are a contiguos block of 10 B objects like so
     // [B0][B2]...[B10] (memory layout)
    

    when you iterate over the array using s, think about what is used

     s[i]
     //s[i] uses the ith B object from memory. Its of type B. It has no polymorphism. 
     // Thats why you use the . notation to call m() not the -> notation
    

    before you converted to an array you just had

     a* s = new B();
     s->m();
    

    s here is just an address, its not a static object like s[i]. Just the address s can still be dynamically bound. What is at s? Who knows? Something at an address s.

    See Ari's great answer below for more information about why this also doesn't make sense in terms of how C style arrays are layed out.

提交回复
热议问题