S.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() (by value, meaning the argument is copied into the parameter). 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.


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

S.4.8 -- The auto keyword
S.4.6 -- Typedefs and type aliases

464 comments to S.4.7 — Structs

  • Mike

    In this example from under the section "C++11/14: Non-static member initialization"

    If I use Uniform, the 1st curly says a semicolon is expected. If I use Direct, then I get an error with x.

    Why can't we use Direct or Uniform initialization? Is it because Uniform is expecting two parameters for rectangle (length and width), even though I'm only specifying the x.length?

    • `x.length` is a variable. You can only initialize it when it gets created. It gets created when you create `x`.
      `x.length = 2.0` is an assignment, not an initialization.

      • Mike

        But isn't x created in the first line?

        Or are you saying that once x is created, then you can't recreate it, which is what I'm doing when I use direct or uniform?

  • Andrea

    I'm using VS 2019 and this line gives the C26451 warning.

    "Arithmetic overflow: Using operator '*' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator '*' to avoid overflow (io.2)."

  • Dear Teacher,
    Please let me suggest you add a section with title "Designated Initializers" and text
    "For Visual Studio 2019 users: After you have created "Windows Desktop Wizard" project, go to "Solution Explorer", double click project's name > select Properties > C/C++ > Language > Standard > select the third (last one) option: ... (std:c++latest draft) > OK.
    Copy following program and paste in V.S. code area. Hit [Ctrl] + [F5].

    This program outputs "50000".
    Variable members not initialized in variable, are initialized with default value in struct." Regards.

    • Alex

      Hi Georges. Designated initializers are on my to-do list to cover when I update the lesson. Thanks for the suggestion!

      • Dear Teacher,
        Please accept my many thanks for you replied my message and many more for your thanks. Also let me post here my suggestion corrected.
        "For Visual Studio 2019 users: After you have created "Windows Desktop Wizard" project, go to "Solution Explorer", right click project's name > Properties > C/C++ > Language > Language Standard > down arrow at the end of the field > the third (last one) option: ... (std:c++latest draft) > OK.
        Copy following program and paste in V.S. code area.

        Run program. It outputs
        Variable members not initialized in variable, are initialized with values (designated initializers) in struct."

  • Rob

    In the code under the heading "Structs and functions", we have "\n", i.e. with double quotes, but lesson 1.5 said we needed to use single quotes when we use \n like this. Both ways seem to work fine for me though (VS 2019 community) - is there any difference between "\n" and '\n'? The relevant code is:

    • It produces the same observable outcome, but '\n' allows `std::cout <<` to use an optimized function to print.
      "\n" is a string. Whenever you pass it to a function, that function has to determine the string's length.
      '\n' is a char. It's length is always 1, so there's no need to determine its length.

      Using quotation marks for characters wastes resources.

  • VerticalLimit

    Hi Nascardriver

    Any pointers to make both codes better ?

    Also for Quiz 2, Iam trying to modifying and use tuple instead of void() just so that i can return multiple values and change the code slightly. In a bigger spectrum will this be beneficial ?
    (so far iam getting -nonIND error which you have already covered. Obviously there is a logical issue which I will try to fix but the question is whether it is worthwhile to modify)

    QUIZ 1

    QUIZ 2

    • - Initialize your variables with brace initializers.
      - Use double literals for doubles.
      - Inconsistent formatting. Use your editor's auto-formatting feature.

      Quiz 1
      - Line 17-18 don't do anything.
      - Unused parameter `earned`.
      You didn't do what the quiz asked you to. If the was on purpose, that's fine. If you did this because you don't know how to do it properly, look at the solution and make sure you understand it.

      > In a bigger spectrum will this be beneficial
      I don't see where you'd use an `std::tuple`. Do it anyway just so you learn how to use it.

      • VeritcalLimit

        Hi Nascardriver
        Thanks for your feedback as always very helpful. Yes I do at times (most often) try to intentionally deviate from what quiz asks for so that I can learn what works and what doesn't hence the question about std::tuple. I prefer to look at the Solutions only at very end once I have published the Quiz. Better indication what I can improve on.
        Could you please clarify the following so that I have a better understanding going forward:

        - Line 17-18 don't do anything. I want the user to enter the amount of ads and how many times ads was clicked on ? (in duplicate quiz Iam running few different ads and I want to see % of each)

        - Unused parameter `earned` : Ive declared 'earned' within dayProfit(double earned) function and then again line 35 and 36.

        - Initialize your variables with brace initializers : I would imagine you are referring to line 5 - 8. If it is as is what potential problem I could run into ? (I will adjust the code regardless)

        Thank you

        • > Line 17-18 don't do anything.

          You're doing the same. Remove those lines.

          > Unused parameter `earned`
          You're not using `earned` in `main` and you're not using the value pass to `dayProfit` through `earned`. `earned` should be a local variable. Or return without storing the result in a temporary.

          > Initialize your variables with brace initializers.
          All your declarations would be better with empty brace initializers to guarantee initialization in all situations, but that's not what I was referring to.
          I meant quiz 2 line 38, 39. You're using copy initialization, which isn't as universal and type-safe as brace initialization.

  • Piyush

    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:

    Bro this is compiled in my compiler.

    How ??

    Is this only related to C++11 version?

    I have the latest visual studio and installed last month, did I missed something ?

    Got that bro c++14 lift this shit up! Thanks

  • Sam

    Here is my solution for Question #2. Any feedback would be appreciated :)!

    • - Initialize your variables with brace initializers.
      - `main`: Missing return-statement.
      - Line 10, 11 should be indented.
      - `Numerator_t` and `Denominator_t` should be declared in `Fraction` and used there too. There's no point in aliasing types if you're not using them everywhere.

      • Sam

        Thank you for your continuous feedback :). Here is my updated code. I decided to remove the typedef completely as having it in the struct and using it on the struct members is superfluous. I also removed the typedefs because I switched from having 2 seperate functions (getNumerator, getDenominator) to having 1 function (getFraction) that gets the entire fraction and returns type "Fraction".

  • Sam

    Here is my solution to problem #1. I would appreciate any feedback I can get! :)

    • - Line 25: Initialize your variables with brace initializers. This line is unnecessary altogether.
      - `main`: Missing return-statement. It should be added for consistency.
      - Use double literals for doubles (100.0 instead of 100).
      - You're using the same name style (lower camel case) for variables and functions, this can lead to confusion.

      • Sam

        Once again, thank you for your excellent feedback. Here is my updated code.

        Also, you stated "You're using the same name style (lower camel case) for variables and functions, this can lead to confusion.", so I changed the functions to all lowercase with a _ seperator. I hope this is what you meant.

  • Edgar J. Wurst

    Any comments on question 1:

    • - Line 43, 44: Initialize.
      - Line 27, 28: There's no need for a variable, you can `return { ... }`.
      - Line 16, 20, 24: You don't need those. Create a `Moneymade` at the top of the function and extract directly into it.

      • Edgar J. Wurst

        So like this?

Leave a Comment

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