tags:

views:

62

answers:

2
#include<iostream>
using namespace std; 
struct My_Class{
  class My_struct{
    int am_i_in_class_or_struct;
  };
};

int main(){
  cout<<sizeof(My_Class)<<endl;
  cout<<sizeof(My_struct)<<endl;
  cout<<sizeof(int);
}

Please Explain: when i executed the above program on Turbo C i got output:

1
2
2 

Now shouldn't the size be same in each case, or at least My_Class should have the same or larger size than My_struct!!

If there are errors in the program please fix them if you can, or else ignore it and concentrate on the question at hand!

I dont trust Turbo C as such... but currently my VS 2008 keeps crashing due to my Ram going bad!

+5  A: 

You are nesting the declarations, but not the data. Declaring one class inside another class does not magically make the data members of the inner class also members of the outer class. Your code is virtually equivalent to a mere

struct My_Class{
};

class My_struct{
  int am_i_in_class_or_struct;
};

with only one difference. In your code the name of the struct is My_Class::My_struct. In my version it is just My_struct. Only the names change. Nothing else. (Actually, there are some other differences with regard to access rights, but it is not immediately relevant to the question as stated.)

AndreyT
So how do i nest the data as well?
strut
How? The "usual" way: data is "nested" by declaring a data member `My_struct my_struct;` in the outer class.
AndreyT
When i use My_Class::My_struct, i get the following error:'My_Class::My_struct' : uses 'My_Class', which is being defined
strut
how to fix this error?
strut
@strut have you tried to use the code from my answer for that?
Amir Rachum
@strut: I don't know how you use it to get such an error. You need to post the code. Doing what I suggested in my comment above does not cause any errors from the compiler. Also, when you are inside `My_Class`, you don't need to use the full name `My_Class::My_struct`. Just `My_struct` is sufficient. But `My_Class::My_struct` should work as well.
AndreyT
+6  A: 

My_Class doesn't contain My_struct, it just defines it. If you'd want to create a My_struct instance from outside My_Class, it will be called My_Class::My_struct.

In order to actually include a My_struct instance in My_Class, you should do

struct My_Class{
  class My_struct{
    int am_i_in_class_or_struct;
  };
  My_struct myStructInstance;
};
Amir Rachum