0

Looking at the sample program:

struct A
{
    float c;
    float d;
    
    A(){};
};

struct B
{
    int a;
    int b;
};



struct C
{
    A a;
    B b;
};

void func(C c)
{
    
}

int main(int argc, char *argv[])
{
    float c, d;
    int a,b;

    func(C{{c,d},a,b});
}

Why does the parameters for A (the floats) need braces since it has a constructor whilst the parameters for B does not?

I have the problem where if I define any sort of constructor I can no longer send in parameters one by one, like the example does with struct B in func().

Am I missing some sort of special construtor to make this possible? Note that the difference is that A does not utilize the default constructor, and that is why it no longer works.

Den Du
  • 1
  • 1

1 Answers1

0

First of all, To read a program one should always start from main function
and here you have written int main(int argc, char *argv[])
you can call it just int main() the reason i'm saying is Go through this link
now after initializing variables, you are calling func(C{{c,d},a,b});
now the control will look if the parameter is valid or not in func
here parameter passed is struct C & it has two struct variable struct A & struct B
First it will go to struct B which has two int type variable & it matches, so compiler would not give error for struct B.
(The reason why it should evaluate first struct B why not struct A,i recommend please read this similar concept is also applied for struct passing)
Now it will check for struct A & it has two float variable, Ok it also matches But struct A has constructor inside So you cannot use aggregate initialization. But you will see compiler will give list initialization error. It's because list initialization is superclass of aggregate initialization.
Now what is aggregate initialization? please read this documantation.
Hope you get the answer and just one more thing: while defining void type function, it's good practice to write return; in the last <3

  • And how would I make this work for A as well? I do not see a clear solution in the links you sent. – Den Du Apr 19 '21 at 06:21
  • Please don't post links to geeksforgeeks. The site is known for it's low quality and wrong information, e.g. https://www.reddit.com/r/learnprogramming/comments/lot6ah/geeksforgeeks_not_a_good_place_to_get_started/. _"while defining `void` type function, it's good practice to write return; in the last"_ I've never heard about it and I've never seen code with it. I would even say that some static code analyzer would give you a warning for redundant code. _"It's because list initialization is superclass of aggregate initialization."_ What does this mean? –  Apr 22 '21 at 22:23