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
2009-07-14 18:54:25
@abelenky-thank u very much
2009-07-14 19:04:44
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
2009-07-14 19:07:32
And you can also simply say "`struct MyStruct`" instead of `typedef`ing an anonymous struct.
sth
2009-07-14 19:20:43
@sth: You are correct, but I'm very old-school. That wasn't always possible, and old habits die hard. :)
abelenky
2009-07-14 19:27:10
@abelenky: I believe it's always been possible to use "struct MyStruct" in C++, but it was illegal in (at least) C90.
David Thornley
2009-07-14 20:34:36
I changed my answer to the plain "struct [name]" format. (hope I got it right... final semi-colon?)
abelenky
2009-07-14 20:47:55
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
2009-07-15 09:24:19
@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
2009-07-15 15:18:18
+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
2009-07-14 18:57:50
+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
2009-07-14 19:00:31
+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
2009-07-14 19:01:04
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
2009-07-15 01:06:45