Latter allocation for derived class

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Latter allocation for derived class



I know that memory for a derived class and it's base classes is allocated as one chunk. But is it possible to allocate additional memory for derived part, after base class has been instantiated?
I suppose, that legally it can be done by reallocation, but what about additional memory?


class foo

int a, b;
//Some properties
;

class bar : foo

bool initialized;
;


int main()

foo *one = new foo();
bar *two = //magic;



`





It's not possible, since bar is a single unit that can't be split. The inheritance doesn't change that.
– Some programmer dude
14 mins ago


bar




1 Answer
1



No, that's impossible. As you said it yourself, the base and the derived parts of an object are allocated in one chunk of memory. But not only that, even if a bigger memory chunk is allocated upfront, and only the base part (foo) is constructed, it is impossible to later construct only the derived part (bar) later.


foo


bar



Note that this is very low level, and should never be done in regular code, unless you are implementing something like std::variant<T,U,...>, which most likely you aren't.


std::variant<T,U,...>


int main()

char *block = new char[sizeof(bar)];
foo * one = new (block) foo();
// The memory block is big enough for bar,
// but there is no way to construct only the bar part
bar * two = // magic is not possible
// this will construct both bar and its parent foo.
// This is bad, since the foo part is constructed twice.
new (block) bar();

delete block;



The best thing is to destroy and to reconstruct the object (don't do it, unless you are implementing a low level library):


int main()

// allocate the memory
char *block = new char[sizeof(bar)];

foo * one = new (block) foo();
work with one....
one->~foo(); // destroy it.

// construct it again, using the derived type.
bar * two = new (block) bar();
work with two
two->~bar(); // don't forget to destroy.

// deallocate the memory.
delete block;






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard