For some reason when I set some default values for the nested structure with a constructor, I get the following error. But it seems the code should work. Can someone tell me where am I going wrong?
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
struct smallDude
{
int int1;
int int2;
// Default constructor
smallDude()
{
int1 = 70;
int2 = 60;
}
};
struct bigDude
{
// structure within structure
struct smallDude second;
}first;
int main()
{
bigDude first = {{2, 3}};
cout<< first.second.int1<<endl;
cout<< first.second.int2;
return 0;
}
Error Output:
main.cpp:28:28: error: could not convert ‘{2, 3}’ from ‘’ to ‘smallDude’
28 | bigDude first = {{2, 3}};
| ^
| |
|
CodePudding user response:
smallDude
has a user-declared default constructor, so it is not an aggregate type, and thus cannot be initialized from a <brace-init-list>
like you are attempting to do.
There are two way you can fix that:
- change the
smallDude
constructor to acceptint
inputs, like @rturrado's answer shows:
struct smallDude
{
int int1;
int int2;
// constructor
smallDude(int x, int y) : int1{x}, int2{y} {}
};
- get rid of all
smallDude
constructors completely (thus makingsmallDude
an aggregate) and just assign default values to the members directly in their declarations, eg:
struct smallDude
{
int int1 = 70;
int int2 = 60;
};
CodePudding user response:
You are missing a smallDude
constructor receiving two int
values:
smallDude(int x, int y) : int1{x}, int2{y} {}