C++ Struct Default Values Initialization

  1. Initialize Default Values in a struct in C++
  2. Steps to Initialize Default Values in a struct in C++

This article will cover how to initialize default values in a struct in C++.

Initialize Default Values in a struct in C++

Mainly, there are two methods to initialize the default values; the first is using the constructor and the second without using the constructor. The latest and most updated method is without using the constructor, and in this article, we will also focus on this method.

But, firstly, it’s important to understand the concept of the struct.

The struct is a data type that can store related data in a single variable. struct is most commonly used to implement an abstract data type and can be either rigid or flexible.

A struct is not an object, so it does not have memory management associated with it and cannot be created as an instance of a class. It also cannot inherit from another struct or class.

A struct is often used to store simple types, such as integers or floating point numbers, but they can also contain more complex types such as arrays, strings, and even other structs.

Let’s discuss the steps to initialize the default values in a struct in C++.

Steps to Initialize Default Values in a struct in C++

The steps to initialize default values in a struct in C++ using the Brace-or-Equal-Initializers are as follows:

  • Start with a code block and type the keyword struct and a name for your data type.
  • Add brackets after the name of your data type and add an opening curly brace ({).
  • Inside the curly braces, add a comma-separated list of variables you want to initialize with default values.
  • Add an equal sign (=), followed by the value you want to initialize each variable.
  • Add a closing curly brace (})
  • At the end of your code block, add one more comma (,) followed by a semicolon (;).

Let’s have an example.

#include <iostream>
using namespace std;
struct hello {
    bool x = true;
    bool y = true;
    bool z = false;
    bool a = false;
    bool b = true;
    bool c = false;
 } demo;
 int main()
 {
     cout << demo.x << demo.y  << demo.z << demo.a << demo.b << demo.c <<endl;
     return 0;
 }

Click here to check the working of the code as mentioned above.

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - C++ Struct

  • Difference Between Struct and Typedef Struct in C++
  • Struct in Class in C++
  • Struct Inheritance in C++