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_ptr) Derived(3);
b_ptr->g(4);
d_ptr->f(5);
seems to be reasonable and LSP is satisfied.
I suspect that this code is standard-allowed when Base and Derived are POD, and disallowed otherwise (because vtbl ptr is overwritten). The first part of my question is: please point out precise precondition of such an overwrite.
There may exist other standard-allowed ways to write over.
The second part of my question is: is there any other ways? What are their precise preconditions?
UPDATE: I do NOT want to write code like this; I am interested in theoretical possiblity (or impossibiliy) of such a code. So, this is "standard nazi" question, not a question "how can I ...". (Has my question to be moved to other stackoverflow site?)
UPDATE2&4: What about destructors? Supposed semantics of this code is "Base instance is (destructively) updated by slice of Derived instance". Let us assume, for the sake of simplicity, that Base class has a trivial destructor.
UPDATE3: The most intersting for me is the validity of access via b_ptr->g(4)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…