简体   繁体   中英

Assigning a derived object to a base class object without object slicing

How can I assign a derived object to a static type of base and without heap allocation?

Basically, I want to know if this is possible:

Base* b = new Derived;

But without new and raw pointers.

You can't assign Derived object to Base variable by value without slicing - Base variable is just not 'big enough' to hold an object of Derived type. Think of it as you still need those sizeof(Derived) bytes of memory to hold an actual object.

However, you can avoid heap allocations.

Allocate it as an automatic variable:

Derived d;
Base* b = &d;

Or as a static variable:

static Derived d;
Base* b = &d;

Or as a global:

//Somewhere in global scope
Derived d;
//...somewhere in function
Base* b = &d;

Or even with placement new on preallocated memory ( disclaimer: do not use this actual code ):

static char memory[sizeof(Derived)];
Base* b = new(memory)Derived;

Finally, raw pointers can be avoided with references, but then you lose the ability to change it after initialization:

Derived d;
Base& b = d;

Either way, you have to allocate enough room for Derived object, and you must ensure that it survives long enough, so you do not access your Base object after original Derived is destroyed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM