Is it possible to pass some parameters to constructor of a class inside a constructor of another class using malloc? I can do that with new. I need to do the same thing with malloc:
(If it does not make sense, consider that I am using a custom allocator instead of malloc)
Class A_Class ... {
public:
B_Class *b;
...
A_Class: ...
{ b = new B_Class (c1, c2, c3);
} // end of constructor
}
Now with malloc:
Class A_Class ... {
public:
B_Class *b;
...
A_Class: ...
{ b = (B_Class*) malloc (sizeof(*b));
??????????????? }
}
mallocallocates raw memory. There’s no point in trying to pass constructor arguments to it because it doesn’t call any constructors.If you have to work with raw memory, it is up to you to construct an object in previously allocated raw memory by using “placement new” syntax
Numerically, the value of
bwill be the same asraw_b, i.e. it is possible to get by without an extraraw_bpointer. But I prefer to do it this way, with an intermediatevoid *pointer, to avoid ugly casts.Be careful when destroying such objects, of course. Custom allocation requires custom deletion. You can’t just
deleteyourbin general case. A symmetrical custom deletion sequence would involve an explicit destructor call followed by raw memory deallocationP.S. You might consider going a different route: overloading
operator new/operator deletein your class instead of spelling out custom allocation explicitly every time you need to create an object.