Class as struct member

Suppose there is a struct with a class as a member of the struct, as in the example below.

1
2
3
4
5
typedef struct _MYSTRUCT
{
    int Num;
    Class MyClass;
} MYSTRUCT;


The class MyClass has a constructor and I wish to specify how it is called in my struct definition. For example, if the constructor of MyClass takes an int as the argument then I wish to specify the int that will be used to construct the class in MYSTRUCT

Is there a way to do this? I know how to do such a thing for class members of classes but not class members of structs.


Regards
Last edited on
In C++ class and struct are basically the same expect for the default access specifier. In struct it is public while in class private. See:

https://www.geeksforgeeks.org/structure-vs-class-in-cpp/
A struct is a class in C++. The only difference is some defaults (class use private by default while struct use public by default). That means you can initialize the data members of a struct the same way you do with a class.

Using default member initializers:
1
2
3
4
5
struct MYSTRUCT
{
    int Num{12};
    Class MyClass{50};
};

Using the constructor's member initializer list:
1
2
3
4
5
6
struct MYSTRUCT
{
    int Num;
    Class MyClass;
    MYSTRUCT() : Num{12}, MyClass{50} {}
};
Last edited on
If you want to define its members out-of-line (say, in a .cpp file):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct my_struct
{
    using int_type = int ;

    class my_class
    {
        public:
            explicit my_class( int n = 0 ) noexcept ; // defined out of line

            int_type value() const noexcept ;  // defined out of line

        private: int_type number ;
    };
};


Definitions:
1
2
3
my_struct::my_class::my_class( int n ) noexcept : number(n) {} // definition of constructor

my_struct::int_type my_struct::my_class::value() const noexcept { return number ; } // definition 


Topic archived. No new replies allowed.