Home > Enterprise >  Nested Structures and using constructor for default value but conversion error
Nested Structures and using constructor for default value but conversion error

Time:11-20

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:

  1. change the smallDude constructor to accept int inputs, like @rturrado's answer shows:
struct smallDude
{
    int int1;
    int int2;

    // constructor
    smallDude(int x, int y) : int1{x}, int2{y} {}
};

Online Demo

  1. get rid of all smallDude constructors completely (thus making smallDude an aggregate) and just assign default values to the members directly in their declarations, eg:
struct smallDude
{
    int int1 = 70;
    int int2 = 60;
};

Online Demo

CodePudding user response:

You are missing a smallDude constructor receiving two int values:

smallDude(int x, int y) : int1{x}, int2{y} {}

Demo

  • Related