I create a structure with another one nested inside it. The doubt is regarding the size of structure if I create a pointer object to the inner structure.
#include <iostream>
usingnamespace std;
struct a
{
struct b
{
int c;
int d;
} *var;
int e;
}aobj;
int main()
{
cout<<"Size of a = "<<sizeof(a)<<endl;
cout<<"Size of a::b = "<<sizeof(a::b)<<endl;
return 0;
}
#include <iostream>
usingnamespace std;
struct a
{
struct b
{
int c;
int d;
} var;
int e;
}aobj;
int main()
{
cout<<"Size of a = "<<sizeof(a)<<endl;
cout<<"Size of a::b = "<<sizeof(a::b)<<endl;
return 0;
}
Output:
Size of a = 12
Size of a::b = 8
What is the reason for the difference in size of the outer structure?
Yes thats what I also figure it out to be, but what would cause sizeof(a::b*) to be equal to sizeof(int).
The next problem that I face with this is while overloading the operator new.
#include <iostream>
usingnamespace std;
struct a
{
struct b
{
int c;
double d;
} *var;
int e;
}aobj;
int main()
{
cout<<"Size of a = "<<sizeof(a)<<endl;
cout<<"Size of a::b = "<<sizeof(a::b)<<endl;
return 0;
}
Output:
Size of a = 8
Size of a::b = 12
Whay does the inner structure's size does not alter the size of the outer structure if it is a pointer?
And it is implemented as an integer within the compiler, so the outer structure's size remains the same whatever be contained in the inner structure.
Now, does overloading the new operator become necessary here because there is no memory allocation for the inner structure's variables and I get a memory fault upon trying to access aobj.var->c
yeah, its not a good coding practice to make an obj if inner member.Its would be better if you write a member function to initialise this pointer by allocating storage for the inner structure.Otherwise there would be no way to utilise this inner structure without accessing it from outside by a::b.