Reputation: 81
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 } {}
};
Upvotes: 4
Views: 180
Reputation: 32982
Your mystruct
would need a suitable constructor which takes an int
ger as an argument, for that.
struct mystruct
{
int myvar;
mystruct(int val) // provide this constructor and good to go!
: myvar{ val }
{}
};
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
{}
};
Upvotes: 4
Reputation: 43
You can initialize s_.myvar inside the constructor like so:
Myclass(int n) {
s_.myvar = n;
}
Upvotes: 3