And to explain why you can't "delete" a member variable ...
When you create an object enough memory is set aside for storing all the member variables. So if you create a
user object it will reserve some memory to store an array of 10 chars and 3 ints. The member variables will be stored next to each other in memory (possibly with padding bytes in between) in the order that you declared them inside the struct.
When you say you want to "delete" a member variable I guess that is because you want to free up some memory so that it can be used for other things. Unfortunately that is not possible, but for good reasons.
All objects of a certain type has the same size. It is not possible to change the size of an object after it has been created. This is the reason why accessing array elements by index is very fast. It just needs to multiply the index with the size of an element and add it to the starting address of the array in order to find the position in memory where the element is stored.
If a language had fine grain control where you could delete any member variable you wanted at runtime it would need to store extra information inside the objects, possibly splitting it up into different parts of memory, and all this would just make the program slower and use
more memory.
If your concern is not about memory usage, and you only want a way to model that a
user can lack a
num3 value then you could represent that using an extra bool.
1 2 3 4 5 6 7 8
|
struct user
{
char y [10];
int num1;
int num2;
int num3;
bool have_num3;
};
|
And then you can use
have_num3 to keep track of if the user has a
num3 or not. If it doesn't (
have_num3 == false) you just don't use
num3 but it will still be there in memory. Another option is to use std::optional that was added in C++17.