CodeBlanks Logo Icon CodeBlanks

Defining structs

Learn to define a struct that combines multiple fields.

struct: grouping data

A struct groups data of different types under one roof. It starts with the struct keyword and members go inside curly braces; a semicolon at the end is mandatory.

struct Point {
    int x;
    int y;
};

Here struct Point is a new type with two int members. This lets you manage the two coordinates of a point together. The same approach can model many real objects like student, book or product.

Defining members

Struct members are written inside curly braces like normal variable declarations. Each member has its own type and name. Member names must be unique within the same struct.

struct Book {
    string title;
    int year;
    double price;
};

Here title is a string, year is an integer, price is a double. To access a member you use the . operator; we will see this in the next lesson. In C++ struct members are accessible from outside by default.

Practice Define the Book struct

Define struct Book. It should have string title;, int year; and double price; members. Do not forget the semicolon at the end. In main, declare a Book b; variable and print cout << "Defined" << endl;.

Starter code

main.cpp
#include <iostream>
#include <string>
using namespace std;

// Define the Book struct

int main() {
    // declare Book b; and print
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <string>
using namespace std;

struct Book {
    string title;
    int year;
    double price;
};

int main() {
    Book b;
    cout << "Defined" << endl;
    return 0;
}

Expected output

Defined

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which keyword is used to declare a struct?

  • type
  • class
  • struct Correct answer
  • record

Explanation: In C++ the struct keyword declares a struct.

2 Fill in the blank: struct definition

Question
struct Point {
    int x;
    int ____;
};
Answer
struct Point {
    int x;
    int y;
};

Explanation: The second member of Point is y.

3 Match concept to explanation

Term Meaning
struct Struct keyword
member Variable inside a struct
{ } Surrounds members

All lessons in Beginner