Conts
Conts

Reputation: 81

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 } {}
};

Upvotes: 4

Views: 180

Answers (2)

JeJo
JeJo

Reputation: 32982

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
   {}
};

Upvotes: 4

IAmPropper
IAmPropper

Reputation: 43

You can initialize s_.myvar inside the constructor like so:

Myclass(int n) {
    s_.myvar = n;
}

Upvotes: 3

Related Questions