cppreference.com
Struct and union initialization.
When initializing an object of struct or union type, the initializer must be a non-empty, (until C23) brace-enclosed, comma-separated list of initializers for the members:
where the designator is a sequence (whitespace-separated or adjacent) of individual member designators of the form . member and array designators of the form [ index ] .
All members that are not initialized explicitly are empty-initialized .

[ edit ] Explanation
When initializing a union , the initializer list must have only one member, which initializes the first member of the union unless a designated initializer is used (since C99) .
When initializing a struct , the first initializer in the list initializes the first declared member (unless a designator is specified) (since C99) , and all subsequent initializers without designators (since C99) initialize the struct members declared after the one initialized by the previous expression.
It's an error to provide more initializers than members.
[ edit ] Nested initialization
If the members of the struct or union are arrays, structs, or unions, the corresponding initializers in the brace-enclosed list of initializers are any initializers that are valid for those members, except that their braces may be omitted as follows:
If the nested initializer begins with an opening brace, the entire nested initializer up to its closing brace initializes the corresponding member object. Each left opening brace establishes a new current object . The members of the current object are initialized in their natural order , unless designators are used (since C99) : array elements in subscript order, struct members in declaration order, only the first declared member of any union. The subobjects within the current object that are not explicitly initialized by the closing brace are empty-initialized .
If the nested initializer does not begin with an opening brace, only enough initializers from the list are taken to account for the elements or members of the member array, struct or union; any remaining initializers are left to initialize the next struct member:
[ edit ] Notes
The initializer list may have a trailing comma, which is ignored.
[ edit ] Example
Possible output:
[ edit ] References
- C17 standard (ISO/IEC 9899:2018):
- 6.7.9/12-39 Initialization (p: 101-105)
- C11 standard (ISO/IEC 9899:2011):
- 6.7.9/12-38 Initialization (p: 140-144)
- C99 standard (ISO/IEC 9899:1999):
- 6.7.8/12-38 Initialization (p: 126-130)
- C89/C90 standard (ISO/IEC 9899:1990):
- 6.5.7 Initialization
[ edit ] See also
- Todo with reason
- Recent changes
- Offline version
- What links here
- Related changes
- Upload file
- Special pages
- Printable version
- Permanent link
- Page information
- In other languages
- This page was last modified on 26 January 2023, at 03:21.
- This page has been accessed 1,042,335 times.
- Privacy policy
- About cppreference.com
- Disclaimers

This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Brace initialization
- 3 minutes to read
- 10 contributors
It isn't always necessary to define a constructor for a class , especially ones that are relatively simple. Users can initialize objects of a class or struct by using uniform initialization, as shown in the following example:
When a class or struct has no constructor, you provide the list elements in the order that the members are declared in the class . If the class has a constructor, provide the elements in the order of the parameters. If a type has a default constructor, either implicitly or explicitly declared, you can use brace initialization with empty braces to invoke it. For example, the following class may be initialized by using both empty and non-empty brace initialization:
If a class has non-default constructors, the order in which class members appear in the brace initializer is the order in which the corresponding parameters appear in the constructor, not the order in which the members are declared (as with class_a in the previous example). Otherwise, if the type has no declared constructor, member initializers must appear in the brace initializer in the same order as they're declared. In this case, you can initialize as many of the public members as you wish, but you can't skip any member. The following example shows the order that's used in brace initialization when there's no declared constructor:
If the default constructor is explicitly declared but marked as deleted, empty brace initialization can't be used:
You can use brace initialization anywhere you would typically do initialization—for example, as a function parameter or a return value, or with the new keyword:
In /std:c++17 mode and later, the rules for empty brace initialization are slightly more restrictive. See Derived constructors and extended aggregate initialization .
initializer_list constructors
The initializer_list Class represents a list of objects of a specified type that can be used in a constructor, and in other contexts. You can construct an initializer_list by using brace initialization:
To use this class, you must include the <initializer_list> header.
An initializer_list can be copied. In this case, the members of the new list are references to the members of the original list:
The standard library container classes, and also string , wstring , and regex , have initializer_list constructors. The following examples show how to do brace initialization with these constructors:
Classes and Structs Constructors
Submit and view feedback for
Additional resources
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Brace (aggregate) initialization for structs with default values
Initializing a struct with default values is trivial:
and initializing a struct with a brace initializer is trivial too:
Suprisingly the init code won't compile, until I remove the default value. So, how would I do the init in such a case? I'd like to keep X a POD without c-tor.
- 4 Just FYI: with c++14, the code compiles. – Mine Sep 6, 2016 at 8:46
- 1 documented here: en.cppreference.com/w/cpp/language/aggregate_initialization – Hayt Sep 6, 2016 at 8:54
- 4 The definition of aggregates was changed to explicitly exclude any class with member initializers; therefore, they are not allowed to use aggregate initialization. C++14 relaxes this restriction allowing aggregate initialization on such types. If the braced init list does not provide a value for that argument, the member initializer takes care of it so basically your code is not possible in C++11 without a C-tor. Only in C++14 – Hatted Rooster Sep 6, 2016 at 8:55
Here is some documentation relevant to the problem:
http://en.cppreference.com/w/cpp/language/aggregate_initialization
In c++11 your code is invalid. In c++14 it is valid again.
In C++11 adding a default initialization prevents braced init from being valid. In C++14, it does not.
A way to solve your problem in C++11 would be to write a constructor with the value for a and the b value with a default.
- Had some misinformation in my original answer. Edited it to the right solution, but left the original answer in because the POD-ness seemed also relevant to OP – Hayt Sep 6, 2016 at 9:00
- I edited out the original and edited portions, merging the part that was still valid in the original one once the edited portion was there. If someone wants to see the history, they can click on the history link. Did my modifications keep your original intent? If not, feel free to roll back, but I encourage you to drop the edit/original pattern. – Yakk - Adam Nevraumont Sep 6, 2016 at 13:28
- The message is still the same. I thought it good at the time (when the message had no upvotes and was not accepted) to indicate to the OP that my initial answer was not the one he was looking for. Now it being accepted + the only answer here I can see that it is better that way. – Hayt Sep 6, 2016 at 13:36
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged c++ c++11 or ask your own question .
- The Overflow Blog
- Building an API is half the battle: Q&A with Marco Palladino from Kong
- Developers think AI assistants will be everywhere, but aren’t sure how to...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- The Stack Exchange reputation system: What's working? What's not?
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
- Temporary policy: ChatGPT is banned
Hot Network Questions
- Why is crystal frequency often multiplied inside a microcontroller?
- How does the GMU44 magnetometer differ from a magnetic compass?
- Mapping Passing Through Point
- How to make those lines in Tikz?
- Opamp with unbalanced rails
- This is a fun little word puzzle based on a fun little number puzzle
- What is the concept of hole in semiconductor physics?
- Is there really a bawdy pun at the conclusion of Romeo and Juliet?
- Preparing a flow chart for thesis outline in TeX
- Can a 13-year-old in the UK accept freelance work?
- broker cancelled life insurance policy without authorization
- Why is the ongoing auction for Silicon Valley Bank started held privately (vs. publicly)?
- DFA that accepts strings whose 10th symbol from the right end is 1
- Why are most US news programs silent about Iran-Saudi deal announced at Beijing on March 10th?
- Why did my flight leave the gear down for the first 10 minutes of flight?
- Is post-hyphenation necessary in "I am a child and adult psychologist..."?
- Experience Learning in the Mir Yeshiva
- What is the covariant version of the dipole moment?
- Movie where a man is abducted by beings believed to be aliens and finds out they were from the future
- How can I heat my buildings without fire in a low-fantasy setting?
- How can I protect /dev/sdX against accidental formatting?
- Is it easier to unclip using a shoe with higher stiffness index?
- Does Latin Word "honestus" Mean English Word "honest"?
- How to extract the internal key of a simple P2TR address?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
10.6 — Struct aggregate initialization

- About this blog

Brace initialization of user-defined types
Uniform initialization syntax is one of my favourite features of Modern C++. I think it’s important, in good quality code, to clearly distinguish between initialization and assignment.
When it comes to user-defined types – structures and classes – brace initialization can throw up a few unexpected issues, and some counter-intuitive results (and errors!).
In this article, I want to have a look at some of the issues with brace initialization of user-defined types – specifically, brace elision and initializer_lists.
Read on for more…
User-defined types
We all know the hoary old interview question: “What’s the difference between structs and classes in C++”. And we all regurgitate the same answer:
- The default access specifier on a struct is public; on a class it’s private
- The default inheritance is public for structs; private for classes.
For Modern C++ there is also a third difference: the way brace initialization is handled.
For a structure, brace initialization performs a direct initialization of its members
For class types, brace initialization results in a call to a constructor.
There’s nothing to stop you adding a constructor to a struct. If you do, the braced initialization list becomes a call to a constructor.
There are some odd corner cases, that might throw you:
Even though we’ve explicitly deleted the two constructors, this code compiles just fine. The reason this works (maybe against your expectations) is that both objects are being direct initialized – that is, the constructors are not being called. The compiler can do this as the attributes are declared as public.
I can ‘break’ this code by actually defining one (or both) of the constructors explicitly
The compiler treats user-defined types with only public attributes as an aggregate type. It will attempt to direct initialize the members unless an appropriate constructor is defined. By extension, if I declare any private attributes aggregate initialization can no longer be applied (you can’t access the private member to initialize it); therefore, the braced initialization list must be used to call a constructor.
Brace elision
Brace elision is a syntactic mechanism to simplify (in some cases) nested structures.
If an aggregate type has a sub-aggregate (that is, another structure) element then the braces around the initializer of the sub-aggregate type may be omitted (elided). The compiler will take as many initializers from the list as required to initialize the element; the remaining iniitializers are then used to initialize any remaining members.
The first two initializations are pretty straightforward. But let’s explore the second two initializations in a bit more detail. The initialization of inner3 is explicit and complete. We could view it like this
The initialization for inner4 uses brace elision. Instead of finding an opening brace for the initialization of Inner::arr , the compiler finds an expression. It assumes that this is meant to be the initialization list for the first (declared) member of Inner . It will then keep consuming initialization-expressions until the member is completely initialized, or it reaches a closing brace.
If we supply too many values, we get an error
In this example, if we supply too few initializers, the remainder of Inner::arr will be value initialized
The question that typically comes up is: why do we have this mechanism? The best answer I can give is std::array .
The STL array class is a thin wrapper around a C-style array. Basically, it’s a struct with a nested C-style array inside. A (highly simplified) implementation could look something like this:
To initialize a std::arra y with values you would have to provide two sets of braces – one set for the std::array , one set for the (nested) C-style array.
This looks awkward; and doesn’t fit in with the initialization syntax of anything else in the language. Brace elision makes our code look more ‘normal’
(If you’re using Clang it will emit a diagnostic about brace-elided initialization for std::array s)
Let’s now look at some corner cases where brace-elision may lead to code “not meeting developer expectations”.
Now we have a structure-within-a-structure.
The first three initializations should be pretty straightforward, based on what we’ve just talked about.
I’ll expand out the initialization of outer4 , as in the previous examples
(Note: The temporary Inner object will be constructed directly into the outer4 member; there will be no copying.)
The initialization for the object outer5 is similar, but this time we are eliding the braces around the temporary Inner object’s arr member.
Using copy initialization seems unnecessary at first glance but is actually a very useful convenience, particularly with class types as we’ll explore later.
For outer6 we have elided all the braces on internal members.
Let’s go all-in on this. This time we have a structure that consists of an array of other structures (replace Outer with std::array to see where this is going…)
The horrible thing about this example is the code that looks it should work, doesn’t; and the code that looks like it shouldn’t work, does!
This is brace elision messing with us. Let’s expand these two examples to see why they work (or fail!) the way they do.
In the second example, by aligning the initializer braces it is easier to see where the problem lies. Brace elision of a member means that the compiler takes initializer values from the supplied braced initializer list. Here, we can see only two values are supplied for Inner::arr; therefore, the second pair of values are value-initialized.
To avoid this confusion you have to make sure you specify all the braces (that is, no brace elision)
If our nested type is a class then we are no longer direct-initializing the object(s) – we are calling constructors.
Given the following code
Our first two definitions give no problems (providing our ADT class supports default construction)
The following declarations give us similar issues to our previous examples.
As before, let’s expand these out and look for the brace elision (or not)
Using copy initialization makes the code a lot more comprehensible.
Technically, there is brace elision going on here; and we should really write
However, hopefully you will agree this actually detracts from the readability of the code.
List initialization of class types
Since one of the design goals of C++ was to emulate the behaviour of built-in types it seems reasonable that you should be able to initialise user-defined aggregate types (containers, etc.) in the same way.
Since the Track class has private data members, using brace initialization results in an attempted call to a constructor. In this case there is no constructor that takes four Position objects.
A std::initializer_list allows a class to be initialized with a list of arguments (although they must be of the same type).
When the compiler creates an initializer list the elements of the list are constructed on the stack (or in static memory, depending on the scope of the initializer list) as const objects. The compiler then creates the initializer_list object that holds the address of the first element and one-past-the-end of the last element. Note that the initializer_list object is very small (two pointers) so can be passed by copy; although you could pass by reference-to-const and save one pointer (at the cost of double-indirect access to the initialiser objects)

A brief look at the implementation of std::initializer_lis t can be enlightening as to its implementation. Here is a (simplified, for clarity) implementation.
The initializer_list object is an instance of a template class that consists of two pointers – one to the first element; and one pointing to one-past-the-end. (Alternatively, an initializer_lis t can be implemented as a pointer plus a length; the results are the same) A simple interface allows client code to access the elements using the Iterator pattern (as with other container-like entities).
The initializer list (and its list of initializing objects) is an r-value expression. Therefore, you must copy from the initializer list into your internal container.
Beware of potential confusion when overloading constructors with std::initializer_list. Given the following class
Different initialization declarations will yield different (and maybe unexpected!) results
The rules are as follows:
- If there is a constructor overload for an initializer list the compiler will strongly prefer this overload to any other.
- To invoke a non-initializer_list overload you must use the parenthesis constructor notation
- The compiler will always prefer a default constructor (empty braces) to an empty initializer_list constructor call.
I’ll leave you with some of our guidelines regarding initialization in C++
- Favour uniform initialization syntax. That is, clearly distinguish between initialization and assignment.
- By extension to the above guideline: always prefer brace initialization.
- Use structs as “Plain Old Data” types only. Avoid constructors and behaviour on structs. In other words, use structs like a C programmer would.
- Use classes for behavioural types.
- Member variables of a class should represent an object’s operational state; and should only be exposed grudgingly.
- Use Non-Static Data Member Initializers wherever possible.
- Use constructors to define an interface to allow clients to override default operational state.
- For initialization of nested objects in aggregate types, prefer copy initialization syntax of the nested object. That way you can exploit brace elision safely; and, perhaps more importantly, to make your code more readable and easier to reason about.
- If you must avoid copy initialization, make sure you avoid brace elision; declare all the braces explicitly.
- Only add initializer_list constructors onto classes that should behave like aggregate types.
- Never overload for both a single object and an initializer list of that type.
- Latest Posts

- Practice makes perfect, part 3 – Idiomatic kata - February 27, 2020
- Practice makes perfect, part 2– foundation kata - February 13, 2020
- Practice makes perfect, part 1 – Code kata - January 30, 2020
Glennan Carnie
Glennan is an embedded systems and software engineer with over 20 years experience, mostly in high-integrity systems for the defence and aerospace industry.
He specialises in C++, UML, software modelling, Systems Engineering and process development.
- Glennan Carnie https://blog.feabhas.com/author/glennan/ Practice makes perfect, part 3 - Idiomatic kata
- Glennan Carnie https://blog.feabhas.com/author/glennan/ Practice makes perfect, part 2 - foundation kata
- Glennan Carnie https://blog.feabhas.com/author/glennan/ Practice makes perfect, part 1 - Code kata
- Glennan Carnie https://blog.feabhas.com/author/glennan/ Function function return return values values*
About Glennan Carnie
1 response to brace initialization of user-defined types.
Thanks for the thorough article!
Leave a Reply Cancel reply
- Search for:
- Build-systems
- C/C++ Programming
- Design Issues
- Industry Analysis
- Uncategorized
- December 2022
- November 2022
- October 2022
- February 2022
- October 2021
- September 2021
- August 2021
- January 2021
- November 2020
- October 2020
- August 2020
- February 2020
- January 2020
- October 2019
- September 2019
- February 2019
- January 2019
- December 2018
- October 2018
- September 2018
- August 2018
- February 2018
- January 2018
- December 2017
- November 2017
- October 2017
- September 2017
- August 2017
- February 2017
- January 2017
- December 2016
- November 2016
- October 2016
- September 2016
- August 2016
- January 2016
- December 2015
- November 2015
- October 2015
- September 2015
- August 2015
- January 2015
- December 2014
- November 2014
- October 2014
- September 2014
- August 2014
- February 2014
- January 2014
- November 2013
- September 2013
- August 2013
- February 2013
- January 2013
- November 2012
- October 2012
- August 2012
- December 2011
- November 2011
- February 2011
- January 2011
- December 2010
- November 2010
- October 2010
- September 2010
- August 2010
- February 2010
- January 2010
- December 2009
- November 2009
- October 2009
- September 2009
aggregate initialization
Initializes an aggregate from braced-init-list
Explanation
Aggregate initialization is a form of list-initialization , which initializes aggregates
An aggregate is one of the following types:
- class type (typically, struct or union ), that has
- no private or protected non-static data members
- no user-provided , inherited, or explicit (since C++17) constructors (explicitly defaulted or deleted constructors are allowed) (since C++11)
- no virtual, private, or protected (since C++17) base classes
- no virtual member functions
The effects of aggregate initialization are:
- Each direct public base, (since C++17) array element, or non-static class member, in order of array subscript/appearance in the class definition, is copy-initialized from the corresponding clause of the initializer list.
- If the initializer clause is an expression, implicit conversions are allowed as per copy-initialization , except if they are narrowing (as in list-initialization ) (since C++11) .
- If the initializer clause is a nested braced-init-list (which is not an expression), the corresponding class member or public base (since C++17) is list-initialized from that clause: aggregate initialization is recursive.
- If the object is an array of unknown size, and the supplied brace-enclosed initializer list has n clauses, the size of the array is n
- Static data members and unnamed bit-fields are skipped during aggregate initialization.
- If the number of initializer clauses exceeds the number of members and bases (since C++17) to initialize, the program is ill-formed (compiler error)
- If the aggregate initialization uses the form with the equal sign ( T a = { args.. } ), (until C++14) the braces around the nested initializer lists may be elided (omitted), in which case as many initializer clauses as necessary are used to initialize every member or element of the corresponding subaggregate, and the subsequent initializer clauses are used to initialize the following members of the object. However, if the object has a sub-aggregate without any members (an empty struct, or a struct holding only static members), brace elision is not allowed, and an empty nested list {} must be used.
- When a union is initialized by aggregate initialization, only its first non-static data member is initialized.
Character arrays
Arrays of character types ( char , signed char , unsigned char , char16_t , char32_t , wchar_t ) can be initialized from an appropriate string literal , optionally enclosed in braces. Successive characters of the string literal (which includes the implicit terminating null character) initialize the elements of the array. If the size of the array is specified and it is larger than the number of characters in the string literal, the remaining characters are zero-initialized.
An aggregate class or array may include non-aggregate public bases (since C++17) , members, or elements, which are initialized as described above (e.g. copy-initialization from the corresponding initializer clause)
Until C++11, narrowing conversions were permitted in aggregate initialization, but they are no longer allowed.
Until C++11, aggregate initialization could not be used in a constructor initializer list due to syntax restrictions.
Until C++14, the direct-initialization form T a { args.. } did not permit brace elision.
In C, character array of size one less than the size of the string literal may be initialized from a string literal; the resulting array is not null-terminated. This is not allowed in C++.
- list initialization
- Pages with unreviewed CWG DR marker
- Data Structure & Algorithm Classes (Live)
- System Design (Live)
- DevOps(Live)
- Explore More Live Courses
- Interview Preparation Course
- Data Science (Live)
- GATE CS & IT 2024
- Data Structure & Algorithm-Self Paced(C++/JAVA)
- Data Structures & Algorithms in Python
- Explore More Self-Paced Courses
- C++ Programming - Beginner to Advanced
- Java Programming - Beginner to Advanced
- C Programming - Beginner to Advanced
- Full Stack Development with React & Node JS(Live)
- Java Backend Development(Live)
- Android App Development with Kotlin(Live)
- Python Backend Development with Django(Live)
- Complete Data Science Program(Live)
- Mastering Data Analytics
DevOps Engineering - Planning to Production
- CBSE Class 12 Computer Science
- School Guide
- All Courses
- Linked List
- Binary Tree
- Binary Search Tree
- Advanced Data Structure
- All Data Structures
- Asymptotic Analysis
- Worst, Average and Best Cases
- Asymptotic Notations
- Little o and little omega notations
- Lower and Upper Bound Theory
- Analysis of Loops
- Solving Recurrences
- Amortized Analysis
- What does 'Space Complexity' mean ?
- Pseudo-polynomial Algorithms
- Polynomial Time Approximation Scheme
- A Time Complexity Question
- Searching Algorithms
- Sorting Algorithms
- Graph Algorithms
- Pattern Searching
- Geometric Algorithms
- Mathematical
- Bitwise Algorithms
- Randomized Algorithms
- Greedy Algorithms
- Dynamic Programming
- Divide and Conquer
- Backtracking
- Branch and Bound
- All Algorithms
- Company Preparation
- Practice Company Questions
- Interview Experiences
- Experienced Interviews
- Internship Interviews
- Competitive Programming
- Design Patterns
- System Design Tutorial
- Multiple Choice Quizzes
- Go Language
- Tailwind CSS
- Foundation CSS
- Materialize CSS
- Semantic UI
- Angular PrimeNG
- Angular ngx Bootstrap
- jQuery Mobile
- jQuery EasyUI
- React Bootstrap
- React Rebass
- React Desktop
- React Suite
- ReactJS Evergreen
- ReactJS Reactstrap
- BlueprintJS
- TensorFlow.js
- English Grammar
- School Programming
- Number System
- Trigonometry
- Probability
- Mensuration
- Class 8 Syllabus
- Class 9 Syllabus
- Class 10 Syllabus
- Class 11 Syllabus
- Class 8 Notes
- Class 9 Notes
- Class 10 Notes
- Class 11 Notes
- Class 12 Notes
- Class 8 Formulas
- Class 9 Formulas
- Class 10 Formulas
- Class 11 Formulas
- Class 8 Maths Solution
- Class 9 Maths Solution
- Class 10 Maths Solution
- Class 11 Maths Solution
- Class 12 Maths Solution
- Class 7 Notes
- History Class 7
- History Class 8
- History Class 9
- Geo. Class 7
- Geo. Class 8
- Geo. Class 9
- Civics Class 7
- Civics Class 8
- Business Studies (Class 11th)
- Microeconomics (Class 11th)
- Statistics for Economics (Class 11th)
- Business Studies (Class 12th)
- Accountancy (Class 12th)
- Macroeconomics (Class 12th)
- Machine Learning
- Data Science
- Mathematics
- Operating System
- Computer Networks
- Computer Organization and Architecture
- Theory of Computation
- Compiler Design
- Digital Logic
- Software Engineering
- GATE 2024 Live Course
- GATE Computer Science Notes
- Last Minute Notes
- GATE CS Solved Papers
- GATE CS Original Papers and Official Keys
- GATE CS 2023 Syllabus
- Important Topics for GATE CS
- GATE 2023 Important Dates
- Software Design Patterns
- HTML Cheat Sheet
- CSS Cheat Sheet
- Bootstrap Cheat Sheet
- JS Cheat Sheet
- jQuery Cheat Sheet
- Angular Cheat Sheet
- Facebook SDE Sheet
- Amazon SDE Sheet
- Apple SDE Sheet
- Netflix SDE Sheet
- Google SDE Sheet
- Wipro Coding Sheet
- Infosys Coding Sheet
- TCS Coding Sheet
- Cognizant Coding Sheet
- HCL Coding Sheet
- FAANG Coding Sheet
- Love Babbar Sheet
- Mass Recruiter Sheet
- Product-Based Coding Sheet
- Company-Wise Preparation Sheet
- Array Sheet
- String Sheet
- Graph Sheet
- ISRO CS Original Papers and Official Keys
- ISRO CS Solved Papers
- ISRO CS Syllabus for Scientist/Engineer Exam
- UGC NET CS Notes Paper II
- UGC NET CS Notes Paper III
- UGC NET CS Solved Papers
- Campus Ambassador Program
- School Ambassador Program
- Geek of the Month
- Campus Geek of the Month
- Placement Course
- Testimonials
- Student Chapter
- Geek on the Top
- Geography Notes
- History Notes
- Science & Tech. Notes
- Ethics Notes
- Polity Notes
- Economics Notes
- UPSC Previous Year Papers
- SSC CGL Syllabus
- General Studies
- Subjectwise Practice Papers
- Previous Year Papers
- SBI Clerk Syllabus
- General Awareness
- Quantitative Aptitude
- Reasoning Ability
- SBI Clerk Practice Papers
- SBI PO Syllabus
- SBI PO Practice Papers
- IBPS PO 2022 Syllabus
- English Notes
- Reasoning Notes
- Mock Question Papers
- IBPS Clerk Syllabus
- Apply for a Job
- Apply through Jobathon
- Hire through Jobathon
- All DSA Problems
- Problem of the Day
- GFG SDE Sheet
- Top 50 Array Problems
- Top 50 String Problems
- Top 50 Tree Problems
- Top 50 Graph Problems
- Top 50 DP Problems
- Solving For India-Hackthon
- GFG Weekly Coding Contest
- Job-A-Thon: Hiring Challenge
- BiWizard School Contest
- All Contests and Events
- Saved Videos
- What's New ?
- Data Structures
- Interview Preparation
- Topic-wise Practice
- Latest Blogs
- Write & Earn
- Web Development
Related Articles
- Write Articles
- Pick Topics to write
- Guidelines to Write
- Get Technical Writing Internship
- Write an Interview Experience
Uniform Initialization in C++
- When do we use Initializer List in C++?
- Initialization of data members
- Use of explicit keyword in C++
- Default Constructors in C++
- Private Destructor in C++
- Playing with Destructors in C++
- Copy Elision in C++
- C++ default constructor | Built-in types for int(), float, double()
- When Does Compiler Create Default and Copy Constructors in C++?
- Why copy constructor argument should be const in C++?
- Advanced C++ | Virtual Constructor
- Advanced C++ | Virtual Copy Constructor
- RTTI (Run-Time Type Information) in C++
- Can Virtual Functions be Private in C++?
- Can Virtual Functions be Inlined in C++?
- A comma operator question
- Result of comma operator as l-value in C and C++
- Order of operands for logical operators
- Increment (Decrement) operators require L-value Expression
- Precedence of postfix ++ and prefix ++ in C/C++
- Modulus on Negative Numbers
- C/C++ Ternary Operator – Some Interesting Observations
- Pre-increment (or pre-decrement) With Reference to L-value in C++
- new and delete Operators in C++ For Dynamic Memory
- Vector in C++ STL
- Arrays in C/C++
- Initialize a vector in C++ (7 different ways)
- Map in C++ Standard Template Library (STL)
- std::sort() in C++ STL
- Difficulty Level : Medium
- Last Updated : 13 Feb, 2023
Uniform initialization is a feature in C++ 11 that allows the usage of a consistent syntax to initialize variables and objects ranging from primitive type to aggregates. In other words, it introduces brace-initialization that uses braces ({}) to enclose initializer values. The syntax is as follows:
Following are some of the examples of the different ways of initializing different types:
If initialized using brace initialization, the above code can be re-written as:
Applications of Uniform Initialization
Initialization of dynamically allocated arrays :
Time Complexity: O(1) Auxiliary Space: O(1)
Initialization of an array data member of a class :
Implicitly initialize objects to return :
Time Complexity: O(1) Auxiliary Space: O(1)
Implicitly initialize function parameter
Please Login to comment...
- adnanirshad158
- suvamtestpurpose
- cpp-data-types
Master C++ Programming - Complete Beginner to Advanced
Complete interview preparation - self paced, full stack development with react & node js - live, improve your coding skills with practice, start your coding journey now.

IMAGES
VIDEO
COMMENTS
The braces around the nested initializer lists may be elided (omitted), in which case as many initializer clauses as necessary are used to
When initializing an object of struct or union type, the initializer must be a non-empty, (until C23) brace-enclosed, comma-separated list of
Use brace initialization with any C++ class, struct, or union.
and initializing a struct with a brace initializer is trivial too: X x = {1, 3};. Suprisingly the init code won't compile, until I remove the
Aggregates use a form of initialization called aggregate initialization, which allows us to directly initialize the members of aggregates. To do
An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value.
Brace elision is a syntactic mechanism to simplify (in some cases) nested structures. If an aggregate type has a sub-aggregate (that is, another
Brace-initialization is a uniform method for initializing data in C++11. For this reason, it is also called uniform initialization.
However, if the object has a sub-aggregate without any members (an empty struct, or a struct holding only static members), brace elision is not allowed, and an
In other words, it introduces brace-initialization that uses braces ({}) to enclose initializer values. The syntax is as follows: