'In C++, can i use structure inside another class?

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.



Solution 1:[1]

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:

  1. Define an inner class within a class, as a form of "namespacing". Use them both as separate (but related) types.
  2. 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 };
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1