Reputation:
Can we define a Class within a Structure? If yes then how? And what will be the syntax of that?
Upvotes: 0
Views: 453
Reputation: 64682
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.
Upvotes: 10
Reputation: 42425
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.
Upvotes: 2
Reputation: 229593
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;
Upvotes: 1
Reputation: 8851
Yes you can. For example:
struct A
{
bool _a;
int _aa;
class B
{
int _b;
public:
B(const int bb):_b(bb){}
};
};
Upvotes: 1