Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a parameter of a struct variable in a class constructor

I am using a struct variable inside a class and I would like to assign the value of a parameter of that variable in the class constructor.

But I can not find a way to compile. could you show me how to do it? This is an example of my code

struct mystruct
{
   int myvar;
}

class myclass
{
   mystruct s_;

public:
   myclass(int n) : s_.myvar{ n } {}
};
like image 532
Conts Avatar asked Mar 02 '23 07:03

Conts


1 Answers

Your mystruct would need a suitable constructor which takes an intger as an argument, for that.

struct mystruct
{
   int myvar;
   mystruct(int val)  // provide this constructor and good to go!
      : myvar{ val }
   {}
};

Or Aggregate Initialization

Since mystruct is an aggregate type you could do the aggregate initialization too. This would be the minimal change required for your case and do not require the constructor in mystruct.

class myclass
{
   mystruct s_;
public:
   myclass(int n)
      : s_{ n } // aggregate initialization
   {}
};
like image 155
JeJo Avatar answered Apr 27 '23 05:04

JeJo