Search

4.7 — Structs

There are many instances in programming where we need more than one variable in order to represent an object. For example, to represent yourself, you might want to store your name, your birthday, your height, your weight, or any other number of characteristics about yourself. You could do so like this:

However, you now have 6 independent variables that are not grouped in any way. If you wanted to pass information about yourself to a function, you’d have to pass each variable individually. Furthermore, if you wanted to store information about someone else, you’d have to declare 6 more variables for each additional person! As you can see, this can quickly get out of control.

Fortunately, C++ allows us to create our own user-defined aggregate data types. An aggregate data type is a data type that groups multiple individual variables together. One of the simplest aggregate data types is the struct. A struct (short for structure) allows us to group variables of mixed data types together into a single unit.

Declaring and defining structs

Because structs are user-defined, we first have to tell the compiler what our struct looks like before we can begin using it. To do this, we declare our struct using the struct keyword. Here is an example of a struct declaration:

This tells the compiler that we are defining a struct named Employee. The Employee struct contains 3 variables inside of it: a short named id, an int named age, and a double named wage. These variables that are part of the struct are called members (or fields). Keep in mind that Employee is just a declaration -- even though we are telling the compiler that the struct will have member variables, no memory is allocated at this time. By convention, struct names start with a capital letter to distinguish them from variable names.

Warning: One of the easiest mistakes to make in C++ is to forget the semicolon at the end of a struct declaration. This will cause a compiler error on the next line of code. Modern compilers like Visual Studio 2010 will give you an indication that you may have forgotten a semicolon, but older or less sophisticated compilers may not, which can make the actual error hard to find.

In order to use the Employee struct, we simply declare a variable of type Employee:

This defines a variable of type Employee named joe. As with normal variables, defining a struct variable allocates memory for that variable.

It is possible to define multiple variables of the same struct type:

Accessing struct members

When we define a variable such as Employee joe, joe refers to the entire struct (which contains the member variables). In order to access the individual members, we use the member selection operator (which is a period). Here is an example of using the member selection operator to initialize each member variable:

As with normal variables, struct member variables are not initialized, and will typically contain junk. We must initialize them manually.

In the above example, it is very easy to tell which member variables belong to Joe and which belong to Frank. This provides a much higher level of organization than individual variables would. Furthermore, because Joe’s and Frank’s members have the same names, this provides consistency across multiple variables of the same struct type.

Struct member variables act just like normal variables, so it is possible to do normal operations on them:

Initializing structs

Initializing structs by assigning values member by member is a little cumbersome, so C++ supports a faster way to initialize structs using an initializer list. This allows you to initialize some or all the members of a struct at declaration time.

In C++11, we can also use uniform initialization:

If the initializer list does not contain an initializer for some elements, those elements are initialized to a default value (that generally corresponds to the zero state for that type). In the above example, we see that frank.wage gets default initialized to 0.0 because we did not specify an explicit initialization value for it.

C++11/14: Non-static member initialization

Starting with C++11, it’s possible to give non-static (normal) struct members a default value:

Unfortunately, in C++11, the non-static member initialization syntax is incompatible with the initializer list and uniform initialization syntax. For example, in C++11, the following program won’t compile:

Consequently, in C++11, you’ll have to decide whether you want to use non-static member initialization or uniform initialization. Uniform initialization is more flexible, so we recommend sticking with that one.

However, in C++14, this restriction was lifted and both can be used. If both are provided, the initializer list/uniform initialization syntax takes precedence. In the above example, Rectangle x would be initialized with length and width 2.0. In C++14, using both should be preferred, as it allows you to declare a struct with or without initialization parameters and ensure the members are initialized.

We talk about what static members are in chapter 8. For now, don’t worry about them.

Assigning to structs

Prior to C++11, if we wanted to assign values to the members of structs, we had to do so individually:

This is a pain, particularly for structs with many members. In C++11, you can now assign values to structs members using an initializer list:

Structs and functions

A big advantage of using structs over individual variables is that we can pass the entire struct to a function that needs to work with the members:

In the above example, we pass an entire Employee struct to printInformation(). This prevents us from having to pass each variable individually. Furthermore, if we ever decide to add new members to our Employee struct, we will not have to change the function declaration or function call!

The above program outputs:

ID:   14
Age:  32
Wage: 24.15

ID:   15
Age:  28
Wage: 18.27

A function can also return a struct, which is one of the few ways to have a function return multiple variables.

This prints:

The point is zero

Nested structs

Structs can contain other structs. For example:

In this case, if we wanted to know what the CEO’s salary was, we simply use the member selection operator twice: myCompany.CEO.wage;

This selects the CEO member from myCompany, and then selects the wage member from within CEO.

You can use nested initializer lists for nested structs:

Struct size and data structure alignment

Typically, the size of a struct is the sum of the size of all its members, but not always!

Consider the Employee struct. On many platforms, a short is 2 bytes, an int is 4 bytes, and a double is 8 bytes, so we’d expect Employee to be 2 + 4 + 8 = 14 bytes. To find out the exact size of Employee, we can use the sizeof operator:

On the author’s machine, this prints:

The size of Employee is 16

It turns out, we can only say that the size of a struct will be at least as large as the size of all the variables it contains. But it could be larger! For performance reasons, the compiler will sometimes add gaps into structures (this is called padding).

In the Employee struct above, the compiler is invisibly adding 2 bytes of padding after member id, making the size of the structure 16 bytes instead of 14. The reason it does this is beyond the scope of this tutorial, but readers who want to learn more can read about data structure alignment on Wikipedia. This is optional reading and not required to understand structures or C++!

Accessing structs across multiple files

Because struct declarations do not take any memory, if you want to share a struct declaration across multiple files (so you can instantiate variables of that struct type in multiple files), put the struct declaration in a header file, and #include that header file anywhere you need it.

Struct variables are subject to the same rules as normal variables. Consequently, to make a struct variable accessible across multiple files, you can use the extern keyword to do so.

Final notes on structs

Structs are very important in C++, as understanding structs is the first major step towards object-oriented programming! Later on in these tutorials, you’ll learn about another aggregate data type called a class, which is built on top of structs. Understanding structs well will help make the transition to classes that much easier.

The structs introduced in this lesson are sometimes called plain old data structs (or POD structs) since the members are all data (variable) members. In the future (when we discuss classes) we’ll talk about other kinds of members.

Quiz

1) You are running a website, and you are trying to keep track of how much money you make per day from advertising. Declare an advertising struct that keeps track of how many ads you’ve shown to readers, what percentage of ads were clicked on by users, and how much you earned on average from each ad that was clicked. Read in values for each of these fields from the user. Pass the advertising struct to a function that prints each of the values, and then calculates how much you made for that day (multiply all 3 fields together).

2) Create a struct to hold a fraction. The struct should have an integer numerator and an integer denominator member. Declare 2 fraction variables and read them in from the user. Write a function called multiply that takes both fractions, multiplies them together, and prints the result out as a decimal number. You do not need to reduce the fraction to its lowest terms.

Quiz Answers

1) Show Solution

2) Show Solution

4.8 -- The auto keyword
Index
4.6 -- Typedefs and type aliases

310 comments to 4.7 — Structs

  • Matt

    I think you may have forgotten to remove a redundant section after an update. In section "Initializing structs" you thoroughly covered initializer lists, but then you covered it again in section "Assigning to structs".

    • Alex

      The initializing structs section covers initialization, whereas the assigning to structs section covers assignment. You can use an initializer list in both places. Just trying to be explicit here, since initialization and assignment are not the same thing (despite being similar in most regards).

  • reznov

    Probably a bit larger than it has to be, but it takes 2 fractions, calculates the deicmal outcome and then also calculates the resulting simplified fraction including base numers base+(a/b).
    I'm finally statisfied for this part of the tutorial, cya guys in 4.8 🙂

    #include <iostream>

    struct Fractions
    {
        int base;
        int numerator;
        int denominator;
    };

    double fractionsMultiply(Fractions first, Fractions second)
    {
        return (static_cast<double>(first.numerator)*static_cast<double>(second.numerator)/(static_cast<double>(first.denominator)*static_cast<double>(second.denominator)));
    }

    int fractionsNumerator(Fractions first, Fractions second)
    {
        return first.numerator*second.numerator;
    }

    int fractionsDenominator(Fractions first, Fractions second)
    {
        return first.denominator*second.denominator;
    }

    Fractions fractionsSimplify(Fractions first, Fractions second)
    {
        Fractions temp{0,0,0};
        temp.numerator = fractionsNumerator(first, second);
        temp.denominator = fractionsDenominator(first, second);

        int i=10;   // only simplifies up to a ratio of 10 for performance reasons.
        while(i>1)
        {
            if(temp.numerator>temp.denominator)
            {
                temp.base=temp.numerator/temp.denominator;
                temp.numerator-=(temp.base*temp.denominator);
            }
            if(temp.numerator%i==0&&temp.denominator%i==0)
            {
                temp.numerator=temp.numerator/i;
                temp.denominator=temp.denominator/i;
                i=0;
            }
            else
                i-=1;
        }
        return temp;
    }

    int main()
    {
        using namespace std;

        Fractions first{0,0,0};
        cout << "Please enter the first fraction (a/b): ";

        cin >> first.numerator;
        cin.ignore(1, '/');
        cin >> first.denominator;

        Fractions second{0,0,0};
        cout << "Please enter the second fraction (c/d): ";
        cin >> second.numerator;
        cin.ignore(1,'/');
        cin >> second.denominator;

        double answer = fractionsMultiply(first, second);
        cout << "The fractions multiplied equals: " << answer << " in decimal values.\n";

        Fractions simple = fractionsSimplify(first, second);

        cout << "The simplified fraction is: " << simple.base << "+" << simple.numerator << "/" << simple.denominator;
        return 0;
    }

  • Hi Alex,

    I think you meant to put a closing curly brace instead of a closing parenthesis on the last line of the second code snippet in the "Assigning to structs" section.

    Thanks for the tutorials!

  • reznov

    So in an attempt to make a foolproof solution for Quiz 1 I tried to test whether the user entered a percentage between 0 and 100, if not it tells the user the rules and asks to enter the number again.
    The same goes for decimal point and decimal comma. Since 0,5 will evaluate as 0 (false) and 0.5 will evaluate as 0.5 (true) I found this a situation where I could legitamately compare a floating point to a boolean value. Now the comparing part works as intended but as I add cin >> ads.earned; into the program it will start an infinite loop of the program running with the false input and I have no clue why.

    • reznov

      it does some crazy stuff with the cout << and cin >> parts of the code when uploading it here, it's all correct in the real code though.

      • reznov

        Here's the problematic part, since it doesn't show properly in the code syntax highlighter.    

        if(ads.earned==false) //Tends to work fine with just cout.
            {
                cout << "Decimal numbers are written with a point, please try again: ";
                cin >> ads.earned; //Falls into inf loop when I add this.
            }

      • reznov

        Also here's the entire code without syntax highlights in case you need to compile and run this to figure out what's happening.

        #include <iostream>

        struct Income
        {
            int shown;      //potential big number
            int clicked;    //percentage value
            float earned;   //small floating point value
        };

        float multiply(Income ads);

        int main()
        {
            using namespace std;

            char again='y';
            while(again=='y')
            {
            Income ads;
            cout << "How many ads were shown today? ";
            cin >> ads.shown;

            cout << "What percentage of ads was clicked today? ";
            cin >> ads.clicked;

            if(ads.clicked<0 || ads.clicked>100)
            {
                cout << "Percentages are a value between 0 and 100, please try again: ";
                cin >> ads.clicked;
            }

            cout << "How much was made per ad on average? ";
            cin >> ads.earned;

            if(ads.earned==false)
            {
                cout << "Decimal numbers are written with a point, please try again: ";
                cin >> ads.earned;
            }

            float totalAdCash = multiply(ads);
            cout << "\nYou have shown " << ads.shown << " ads today.\n" << ads.clicked << " percent of the viewers clicked an ad.\n" <<
                    "You have made an average " << ads.earned << " dollars per ad clicked.\n" << "You have made a total of " <<
                    totalAdCash << " dollars today, you rich bastard.\n";

            cout << "\nWould you like to repeat? (y/n): ";
            cin >> again;
            cout << "\n";
            }

            return 0;
        }

        float multiply(Income ads)
        {
            return static_cast<float>(ads.shown)*static_cast<float>(ads.clicked)*ads.earned;
        }

        • reznov

          It appears the cin >> function crashes (fails to read till program ends) when getting an input with a comma leaving my again defined as y and therefor looping the program... None the less I'm still clueless on how to fix it :\

    • Alex

      Sounds like cin is going into failure mode. I talk about this (and how to fix it) in lesson 5.10.

  • reznov

    Oh man Code::Blocks 16.01 is godlike. It pretypes the semicolon when it recognizes you are trying to declare a struct 🙂 Will never be forgetting that as long as I just keep using this IME.

  • Kılıçarslan

    Hi,this code

    doesn't compile in visual studio 2015.You said it compiles with using both the non-static initialization and the uniform list initialization.Here is the build log :

    1>c:\users\hun\documents\visual studio 2015\projects\consoleapplication1\consoleapplication1\consoleapplication1.cpp(18): error C2440: 'initializing': cannot convert from 'initializer list' to 'Triangle'
    1>  c:\users\hun\documents\visual studio 2015\projects\consoleapplication1\consoleapplication1\consoleapplication1.cpp(18): note: No constructor could take the source type, or constructor overload resolution was ambiguous

    Can you help me?

  • maddin

    Hey Alex,

    I have a question concerning the initialization of my struct:
    In

    my compiler (g++ 4.8.4) displays the error: extended initializer lists only available with -std=c++11 .. .

    Okay, if I initialize my struct like you did with

    everything is fine. However, is it just a new c++11 feature or is it a case of c++11- code I have read over above?

    Thx for the great Tutorial 😉

    • Alex

      Older compilers support initializing structs with an initializer list as long as it's done during initialization, but not assignment. In C++11, this was extended to assignment as well.

      I've updated the lesson to include this point.

  • Dekasi

    Can you help me to figure out how to declare a variable (it's named p) of type M as part of the variable sa of type S? There is a comment after the line where I think that variable should be declared. I tried to declare it but the compiler says that there is invalid use of struct S::M.

    • Alex

      There are two things you can do:

      or

  • bert

    Typo:

    "One of the simplest aggregate data type(types) is the struct."

  • Raquib

    Quoting from the lesson-

    "C++ allows us to create our own user-defined aggregate data types. An aggregate data type is a data type that groups multiple individual variables together. One of the simplest aggregate data type is the struct. A struct (short for structure) allows us to group variables of mixed data types together into a single unit."

    So struct is a way of grouping multiple data-types into a single unit. In the example- Point3d is a data-type (aggregated data-type) having three different properties- x, y & z.

    In a function the data-type before the function name is the return type of the function. What the function is returning. Previously when we mentioned an int/double/char before a function, it meant that the function will return a single element (function has single property) of the respective data-types.

    Ex-

    Similarly ‘Point3d’ here also mentions a return type of a function, just instead of having a single property it has 3 distinct properties x,y &z. It’s treated exactly as a normal data_type with additional cool features.

    when we defined a variables previously we did it with single statement-

    Ex:

    So if we wrote a program, to get all these info. We probably needed to write 3 different functions (considering not using an array) userID(), userAge() & userSalary(). This can become cumbersome very quickly.

    We will be using struct so that we can do it quickly and efficiently. Evidently all these information is about the user, and will change depending on the user. So why not group them, that’s exactly what struct allows us to do.

    Ex.

    This is how struct works, I hope I could clarify your doubt and did not confuse you more than you were  😛 😀

    Thanks.

  • Tejaswi

    I didnt understand that part where you use the struct_name as the data_type for a function. Is it possible do that, How does it work??

    • Alex

      When you define a struct in C++, you're creating a custom type. So just like when you declare:

      You can do this:

  • Raquib

    Hi Alex,

    "Unfortunately, in C++11, the non-static member initialization syntax is incompatible with the initializer list and uniform initialization syntax, so you’ll have to decide which one to use. For structs, we recommend the uniform initialization syntax." -

    >> I didn't understand it. What is a non-static member (is it the opposite of static duration variable? meaning automatic duration variable?? I am confused)...

    can you clarify that, perhaps an example illustrating what is allowed and what is not (if you think it will be intuitive after you clarify then no need of an example??)

    Thanks.

    • Alex

      A non-static member is any struct member that is not declared using the static keyword. So yes, automatic duration. I've added an example to the lesson.

  • Abhi

    Hi,

    In quiz 1, if I use a different function for taking values from user, it returns wierd numbers, why so?

    What's the mistake?

    • Alex

      Because TakeValue() is not assigning values to main's version of ad, it's assigning values to its own local version of ad.

      You could fix this by making TakeValue() return ad, and assign that return value to the ad variable in main.

    • Tejaswi

      This might be the case if your using online compilers like 'codechef.com'. They ask for custom input separately...there exists no terminal window. Same thing happened to me, I got weird values, but then realized I hadnt given custom input. Then it worked fine.

  • K

    Hi, sorry if this is a stupid question but I'm a bit confused with the solution to question 2. I did everything the same except instead of

    it was

    When it was put this way, the answer to (1/2)*(1/2)=0 instead of 0.25 so I changed it to your solution and it comes out as 0.25. As (1/2)*(1/2)=(1*1)/(2*2) I'm just confused. What causes this?

    Again sorry if I'm just having a dumb moment!

    • Alex

      static_cast(f1.numerator / f1.denominator) does an integer division (which causes data loss) and then casts the result to a float (too late).
      static_cast
      (f1.numerator * f2.numerator) does an integer multiplication (which does not cause data loss) and then cases the result to a float so the division that happens just after is a floating point division, not an integer division.

  • Seolhyun

    Hi Alex,
    Could you please point out what wrong with may code

    I receive the error:
    |64|error: no matching function for call to 'Triangle::Triangle(<brace-enclosed initializer list>)'|
    Structs\main.cpp|64|note: candidates are:|

    Finally, thank for your tutor. It's really useful.

    • Alex

      From the lesson, "Unfortunately, in C++11, the non-static member initialization syntax is incompatible with the initializer list and uniform initialization syntax."

      You've got a non-static member initialization and you're trying to use uniform initialization, so you're running into this issue. Remove the non-static member initialization values.

  • Jim

    Alex,

    I believe the wording in this lesson is a bit misleading! In the context of this lesson you defined a struct Employee with 3 members (fields).

    Therefore,you just define Employee a new data type here didn't you?

    After that you wrote that Employee is a variable in various places, this is a bit confusing.

    It seems to me that joe, and frank should be the variable that you are referring to here. Employee can not be change in this context, so it can't be a variable

    • Alex

      > Therefore,you just define Employee a new data type here didn’t you?

      Yes.

      > After that you wrote that Employee is a variable in various places, this is a bit confusing.

      I can't find where I said anything like that. Can you paste in the sentence where you think I said this so I can fix it?

      I did say, "When we define a variable such as Employee joe", the implication here is that joe is the variable, and Employee is the type.

      Thanks!

      • Jim

        Alex,

        The last sentence of your reply cleared up my confusion.
        Employees is the type and joe is the variable.

        "In order to use the Employee struct, we simply declare a variable of type Employee"

        It might have helped if you would have written... we simply declare a variable using the employees first name for the type employee. e.g. employee joe.

        Thanks

  • J3ANP3T3R

    Need help. i noticed that in the quiz i made a wrong script as i had to create two integer variables. the answer to the quiz looks better and faster. however, i should still be able to do some initializing on my struct but it wont let me. says "error C2440: 'initializing': cannot convert from 'initializer list' to 'WebsiteEarnings'" what does it mean ?

    struct WebsiteEarnings
        {
            int shown = 0;
            int clicked = 0;
            double earned = 0.0;
        };

    void printWebsiteEarnings(WebsiteEarnings checkWebInfo)
    {
        checkWebInfo.earned = double(checkWebInfo.shown * checkWebInfo.clicked);
        std::cout << checkWebInfo.shown << " X " << checkWebInfo.clicked << " X " << checkWebInfo.earned << std::endl;

    }

    void optCalculateWebProfit()
    {
        std::cout << "nEnter number of Ads shown t: ";
        int ads{ 0 };
        std::cin >> ads;

        std::cout << "nEnter Clicked Percentage t: ";
        int clicked{ 0 };
        std::cin >> clicked;

        WebsiteEarnings webInfo {ads,clicked};
        printWebsiteEarnings(webInfo);

    }

    the error message points to this line of code
    WebsiteEarnings webInfo {ads,clicked};

    • Alex

      You're using both non-static member initialization AND an initialization list. As the lesson says, in C++11, you can only use one or the other. Although this restriction was removed in C++14, it appears Visual Studio 2015 still doesn't support this.

  • Pooja

    Hello Alex,

    Out of curiosity I am asking, Why Union and register types are not included in this chapter?
    Are they available in some other chapter?

  • John

    For organizational purposes, it seems that I might want to define a struct within another struct. For example, in the section "Nested Structs" you write the code

    If the struct "Employee" will only ever be used within the struct "Company," then I could combine the two into

    The compiler has no problem allowing me to do this, but you don't mention it in the lesson. Is doing so acceptable/recommended in C++?

  • Jim

    Alex,
    Shouldn't this be ...Triangle x.length = 2.0 ?
    int main()
    {
        Triangle x; // length = 1.0, width = 1.0
        x.length = 2.0;

        return 0;
    }.

    When we initialize Employee joe do we supply leading commas if we don't supply an id and age like so Employee joe = { , , 60000.0 } ?

    • Alex

      1) Yes. I've updated the example to make it clearer that the 2.0 is just a standard assignment.
      2) I'm not aware of any way to skip initialization values to the left of an initialized value. Why C++ doesn't support this in the way you suggest, I don't know.

  • Patrick

    Hi Alex,

    I am a new in C++ programming and really appreciate your site. By completing your coding quizzes I try to follow best practices that you shared with us and articles written by other programming experts.

    For the line in quiz1 answer: (ad.adsShown * ad.clickThroughRatePercentage / 100 * ad.averageEarningsPerClick) << endl;

    Based on your comment line above the print statement, should this line be changed to: (ad.adsShown * (ad.clickThroughRatePercentage / 100) * ad.averageEarningsPerClick) since we want only clickThroughRatePercentage to divided by 100 and not the multiplication of adsShown and clickThroughRate Percentage?

    As best practice, I think a calculation formula is best to be assigned to variable and then use that variable to print in the console. I can imagine that this will provide debugging advantages (monitoring variables in Watch Window) especially in larger programs?

    Finally, I also tried to create a struct in a separate cpp file but I was unable to reference to the struct under main(). Can I use a class type file for a struct, make a reference in the header file and include the header file that contains the struct in the main source file? When I copy the struct back in the main() source file, my code is building without any compiler errors.

    • Alex

      Parenthesizing ad.clickThroughRatePercentage / 100 doesn't change the answer (since multiplication and division have the same precedence and are resolved left to right), but it may help improve understanding.

      Assigning values to variables can definitely make debugging easier.

      For the last part, I'm assuming you're talking about a struct declaration and not an instantiated struct variable? If so, you can put the struct declaration in a header file and then #include it wherever you need it. If you meant an instantiated struct variable, you'll need to declare a variable forward declaration (using the extern keyword) in any other file you want to use that variable in.

      • Patrick

        Thank you, Alex

        I put the struct in the header file and this resolved my problem. I try to use class and header files for functions and now structs in every exercise just to get used of managing multiple files in a project.

  • Sharaf

    • sharaf

      see the question in comment,

      • Alex

        when b2.brea++ is evaluated, the compiler makes a temporary copy of b2.brea (value 15), increments the real b2.brea (value 16), and then evaluates the expression to the copy of b2.brea (value 15). Since nothing is done with this evaluated value, it is discarded.

        The real b2.brea still has value 16.

        • sharaf

          oh! it means when post increment is used to use the temporary file we must use it at that time

          i guess my assumpsion is correct

  • Sharaf

    if we have to use a struct we should define a variable under stuct

    can we in the same way initialize a function

    like you have done above

    And can you tell me what you have done in

    • Alex

      I'm afraid I don't understand your first question.

      As for the second one, sure. getZeroPoint() returns a Point3d, which we're using as an initializer for a Point3d named zero.

      Same thing as this really:

      just with a struct instead of an int.

      • sharaf

        why are you afraid?

        my question says:

        by declaring calc() as int data type, it means function can pass only int to other function (is it correct?)

        now my question is by declaring a function as
        a struct name as you have done

        does this mean this function can only pass Point3d() structure?

        i hope i am clear

        • Alex

          Saying "I'm afraid I don't understand" is just a polite way of saying "I don't understand". I forget that sometimes these things don't always translate well to non-native English speakers. 🙂

          And yes, you are correct in your assessment. The getZeroPoint() function will return a Point3d back to the caller.

  • c++ lover

    i want to ask you a silly doubt

    if i replace

    by

    then can you explain the process

  • Heitor

    Just one quick question: Is it possible to use Structs in arrays?

    • Shiva

      Just like for any other datatype, you can create an array of structs, if that's what you mean. e.g.

      Or if you mean arrays inside structs, I think you can do that too:

      Hope that helps. 🙂

  • Shiva

    Quick question on solution to Quiz 2) above:

    Is there any specific reason to define struct member variables of the same type in different lines:

    instead of defining them in a single line:

    ? Both compiles fine. Is it a matter of being a better programming practice?

  • C++ novice programmer

    void printInformation(Employee employee)
    {
        std::cout << "ID:   " << employee.id << "\n";
        std::cout << "Age:  " << employee.age << "\n";
        std::cout << "Wage: " << employee.wage << "\n";
    }

    void printInformation(Employee)
    {
        std::cout << "ID:   " << Employee.id << "\n";
        std::cout << "Age:  " << Employee.age << "\n";
        std::cout << "Wage: " << Employee.wage << "\n";
    }
    Thank you for this very nice tutorial sir Alex!

    why do we need to use that 'employee' starting with small letter? I tried to use only the 'Employee' with capital in the second example but it says error type name not allowed.

    • Alex

      Employee is the name of the type, and employee is the name of the variable. Similar to "int x", where int is the type and x is the name of the variable.

  • Anupam

    Would a structure declaration not consume memory even when "non-static member initialization" is used?

  • Josh

    frank.wage should be initialized to 0, in my point of view.

    Also refer to:
    http://stackoverflow.com/questions/1069621/are-members-of-a-c-struct-initialized-to-0-by-default

  • Jane

    #include <iostream>
    #include <string>
    #include <fstream>
    #include <iomanip>
    #include <cmath>
    using namespace std;
    enum CarMake
    {Audi = 'A', Chrysler = 'C', Ford = 'F',
    Honda = 'H', Lexus = 'L', Mercedes = 'M', Nissan = 'N', Porche = 'P', Volvo = 'V'};
    struct Date  //declare the struct prototype
    {
      int day;
      int month;
      int year;
    };
    struct Car
    {
       string firstname;
       string lastname;
       int costofthecar;
       Date dateofpickup;
       CarMake cartype;
    };
    int main()
    {
        Car information;
        cout << information.cartype.Audi;//error line

        return 0;
    }

    //Please Why does the compiler say expression must have class type

    • Alex

      This line is incorrectly constructed. I'm not even clear on what you're trying to do.

      I think you may have meant to do this:

    • Shiva

      Audi = 'A' ?

      How can enumerators be assigned character constants? I thought enumerators can be assigned only integer values.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]