Structs

8.2 - Struct initialization


This lesson uses the previous Dog struct example:

struct Dog
{
    std::string name;
    int age;
    std::string breed;
};

Once we define the struct we can create variables with the type Dog just like any other types like int or std::string. Exclusively for struct or class where all its fields are public, the aggregate initialization can be used. All the fields are put in curly braces in the same order in the struct definition. For example:

Dog spike{"Spike", 78, "American Bulldog"};
// Sets name = "Spike", age = 78, and breed = "American Bulldog".

Your task is to create the variable children_book and initialize it to have these values:

  • title: "The Very Hungry Caterpillar"
  • author: "Eric Carle"
  • year_published: 1969
#include <iostream> #include <string> struct Book { std::string title; std::string author; int year_published; }; int main() { // Create children_book after this line! // Prints out its fields. std::cout << "Title: " << children_book.title << std::endl; std::cout << "Author: " << children_book.author << std::endl; std::cout << "Year published: " << children_book.year_published << std::endl; }