Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ struct definition - how to define a member struct with a single argument in its constructor

Tags:

c++

struct

Simple question. I have a struct which has a member that is also a struct. The member struct takes one string parameter on construction. However, in the class definition, the compiler doesn't allow it to be instantiated from there. I.e. the following is not allowed:

struct StructName {
   string       str;
   OtherStruct  other_struct("single string param")   
};

So I tried not giving it a parameter which fails because it has to take one:

struct StructName {
   string       str;
   OtherStruct  other_struct;

   StructName(string arg);  
};

I'm new to C/C++ so I'm sorry if it's an idiotic question.

Thanks.

like image 476
ale Avatar asked Dec 21 '22 12:12

ale


1 Answers

Use an initialization list:

struct StructName {
   string       str;
   OtherStruct  other_struct;

   StructName(): other_struct("init string") { }   
};

You can also take an argument to StructName and pass it along to other_struct, such as:

StructName(string arg): other_struct(arg) { }
like image 149
yan Avatar answered Jan 11 '23 22:01

yan