Jay
Jay

Reputation:

Class in a Structure in C++

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

Upvotes: 0

Views: 453

Answers (5)

Chris
Chris

Reputation:

struct s1
{
    class c1
    {
            int n;
            public:

    };
};

Upvotes: -1

abelenky
abelenky

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

Piotr Dobrogost
Piotr Dobrogost

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

sth
sth

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

Indy9000
Indy9000

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

Related Questions