tags:

views:

209

answers:

5

Can we define a Class within a Structure? If yes then how? And what will be the syntax of that?

+9  A: 

Yes. Here is an example of declaration, implementation, and usage.

Declaration

struct MyStruct
{
    int m_Int_in_Struct;

    class MyClass
    {
        public:
            MyClass(); // default constructor
            int m_Int_in_Class;
    };
};

Implementation

MyStruct::MyClass::MyClass() // Constructor Implementation
{
    m_Int_in_Class = 5; 
}

Usage

int main(int argc, char* argv[])
{
    MyStruct::MyClass* newObject = new MyStruct::MyClass();
    newObject->m_Int_in_Class = 10;
}

Hope this answers your question.

abelenky
@abelenky-thank u very much
If this is what you wanted, please mark the answer as "Accepted" (the check-mark on the left-side, near the Up-Down voting.).
abelenky
And you can also simply say "`struct MyStruct`" instead of `typedef`ing an anonymous struct.
sth
@sth: You are correct, but I'm very old-school. That wasn't always possible, and old habits die hard. :)
abelenky
@abelenky: I believe it's always been possible to use "struct MyStruct" in C++, but it was illegal in (at least) C90.
David Thornley
I changed my answer to the plain "struct [name]" format. (hope I got it right... final semi-colon?)
abelenky
Here's a question for you. If "MyStruct" was a POD before, and you add the class into the definition, is "MyStruct" still a POD?
Richard Corden
@Richard: I'm not 100% sure, but I think so. In my example, class is a definition that happens to appear inside the struct. But definitions don't take up any memory. I still expect sizeof(MyStruct)==4.
abelenky
+1  A: 

Yes you can. For example:

struct A
{
 bool _a;
 int  _aa;

 class B
 {
  int _b;
  public:
  B(const int bb):_b(bb){}
 };
};
Indeera
+1  A: 

In C++ the only difference between a class and a struct is that class-members are private by default, while struct-members default to public. So defining a class inside a struct works the same way as defining a class inside another class:

struct A {
  class B {};
  B b;
};

A::B b2;
sth
+2  A: 

Structure in C++ is ordinary class with all members public.
Because you can nest one class declaration in another class declaration (creating nested class) you can do the same within a structure.

Piotr Dobrogost
A: 
struct s1
{
    class c1
    {
            int n;
            public:

    };
};
This code has a dangling "public:", isn't formatted, or code-blocked, and has no explanation or supporting material. I'm shocked it got an up-vote, and I am down-voting.
abelenky