Marc Casals Marc Casals - 1 year ago 47
C++ Question

Declaration of inner struct in another struct results in error: invalid use of struct

This is my first question here. I started learning C++ this summer and I have a little problem with this part of the code:

struct Contact{
char name[30];
char surname[50];
int age;
struct Born{
int day;
int month;
int year;
};
char mail[50];
};


Well, I think this part of the code is OK, but I have this function to enter information and I don't know what I'm doing wrong.

Contact readContact(){
Contact c;
cout<<"\t NAME: ";
cin.getline(c.name,30);
cout<<"\t SURNAME: ";
cin.getline(c.surname,50);
cout<<"\t AGE: ";
cin>>c.age;
cout<<"\t BIRTHDATE:";
cin>>c.Born.day>>c.Born.month>>c.Born.year;
cout<<"\t EMAIL: ";
cin.getline(c.mail,50);
cin.ignore();
return c;
}


The message that I get is this:


invalid use of 'struct Contact::Born'|


Maybe is a very simple error but I'm new at coding and I can't see what I'm doing wrong. :(

Answer Source

As mentioned in a comment, the symbol Born is a type, much like Contact is.

The simple solution is to declare the structure as an anonymous type for a variable:

struct Contact{
    char name[30];
    char surname[50];
    int age;
    struct /* No type name here */ {
        int day;
        int month;
        int year;
        } Born;  // Member variable name here
    char mail[50];
};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download