Sadique
Sadique

Reputation: 22823

Nesting of Structs and Classes

#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!

Upvotes: 2

Views: 253

Answers (2)

Amir Rachum
Amir Rachum

Reputation: 79625

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;
};

Upvotes: 6

AnT stands with Russia
AnT stands with Russia

Reputation: 320421

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.)

Upvotes: 5

Related Questions