I am new to C++ oop and I am skeptical about using structure inside class. if yes, how to get data from it. I've tried searching online but couldn't find an satisfactory answer.
Asked
Active
Viewed 197 times
0
-
Yes, you can use a structure inside a class. You use it like you would any other structure. Do you have any specific problem? (Get a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and start reading instead of relying on guessing the right words to search for.) – molbdnilo Mar 10 '22 at 12:49
-
2`struct Foo { int x; struct Bar { int y; }; };` works just fine. – Eljay Mar 10 '22 at 12:53
-
1You need an instance of the nested `struct` to get or set data from it. Just declaring a `struct` inside a `struct` does not make an object of the nested struct. – drescherjm Mar 10 '22 at 13:02
-
"how to get data from it" You'd need an instance of your inner struct to get non-static data from. In general, there's no problem with *types* being members of classes – Caleth Apr 06 '22 at 11:53
1 Answers
0
In the answer below each appearance "class" can be replaced with "struct". This is because in C++ a struct is more or less a class where the default access is "public".
It is not clear from your question what exactly you'd like to do. Having a class inside a class can have one of the following meanings:
- Define an inner class within a class, as a form of "namespacing". Use them both as separate (but related) types.
- Define an inner class within a class in order to use it an a type for a member variable.
Example of declaring the classes:
class Outer
{
public:
struct Inner
{
int m_ia{ 0 };
int m_ib{ 0 };
};
Inner m_inner;
};
Usage example:
int main()
{
// Usage of the inner class as a separate type:
Outer::Inner inner;
inner.m_ia = 333;
inner.m_ib = 444;
// Usage of the inner class as a part of the outer class:
Outer outer;
outer.m_inner = Outer::Inner{ 111,222 };
}

wohlstad
- 12,661
- 10
- 26
- 39
-
Hoever if you ever want to use forward declaration of Inner, you are bound to fail. – KIIV Jun 01 '22 at 14:04
-
I agree. But this is what the OP would like to do (use an inner class). – wohlstad Jun 01 '22 at 14:12