I have a plain old C struct:
struct eggplant {
double *ptr1;
double *ptr2;
... // many more
}
and a function that manages the allocation the memory pointed to by the pointers, and returns a new eggplant instance:
struct eggplant *create_eggplant(int n);
The above function allocates a chunk of memory (including space for the newly created struct) and distributes it to the pointers.
I want to extend struct eggplant in C++11. I could do that by keeping a pointer to the struct as a
class EggPlant {
...
private :
struct eggplant *plant;
}
or I could try via
class EggPlant : private struct eggplant {
...
}
The first option allows me to use the create_eggplant function. However, the second option looks more straightforward from a conceptual point of view (the class EggPlant is an eggplant, it doesn't have one).
I tried
this = create_eggplant(...);
in the constructor but that does not work for the obvious reason that you cannot overwrite a pointer to a class that you are constructing (lvalue required).
Can I inherit the struct but still use my create_eggplant function in some useful way? Or, is it anyway better to keep a pointer to the struct?
Your choice to have struct eggplant *create_eggplant(int n); manage its own memory is in conflict with C++ inheritance. Inheritance also implies management of the location of the base object.
If you changed your C function to return a copy:
struct eggplant create_eggplant(int n);
You could also inherit from that class:
class EggPlant : private eggplant {
EggPlant(int n) : eggplant{ create_eggplant(n) }
{
}
...
};
No, you would need a new function if you wish to inherit. If you must use the existing function a member is the best you will be able to manage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With