ligin pc
ligin pc

Reputation: 31

Initializing a nested structure throws error in C++

I am learning structures in C++. Got the following error while executing the code:

Error: Too many initializer for CompData.

It would be great if someone could point out the mistake.

Code:

#include <iostream>
#include <string>

struct EmpData
{
    std::string name;
    int age;
    double salary;
};

struct DepartmentData
{
    std::string departmentName;
    struct EmpData;
};

struct CompData
{
    std::string compName;
    struct DepartmentData;
};

int main()
{
    CompData DeltaF 
    {
        "DeltaF",
        {
            "Product Development",
            {
                "Steve", 35, 1223
            }
        }
    };
    
}

Upvotes: 0

Views: 53

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122458

Here:

struct DepartmentData
{
    std::string departmentName;
    struct EmpData;
};

You declare a structure EmpData, full name is DepartmentData::EmpData. It is a different type than EmpData you declared and defined above. If you want DepartmentData to have a member of type EmpData you can remove struct and need to give it a name:

struct DepartmentData
{
    std::string departmentName;
    EmpData empData;             // member of type EmpData called empData
};

Same for the DepartmentData member of CompData. If you fix those, your code compiles without errors.

Upvotes: 2

Related Questions