0

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
            }
        }
    };
    
}
2
  • 7
    struct EmpData; doesn't do what you think it does. You need something like EmpData data; Commented Jul 12, 2021 at 13:46
  • In C++ you don't need to prepend struct keyword to declare a variable with a structure type, like you need with C. What you are actually doing in your DepartmentData type is declaring a nested type. Commented Jul 12, 2021 at 13:53

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.