Is it allowed to write an instance of Derived over an instance of Base?

后端 未结 4 2239
傲寒
傲寒 2020-12-11 22:35

Say, the code

    class Derived: public Base {....}

    Base* b_ptr = new( malloc(sizeof(Derived)) ) Base(1);
    b_ptr->f(2);
    Derived* d_ptr = new(b         


        
4条回答
  •  盖世英雄少女心
    2020-12-11 23:13

    You are initializing the same piece of memory twice. That won't end well.

    Suppose for example that the Base constructor allocates some memory and stores it in a pointer. The second time through the constructor, the first pointer will be overwritten and the memory leaked.

提交回复
热议问题