Structures in C++

We often come around situations where we need to store a group of data whether of similar data types or non-similar data types. We have seen Arrays in C++ which are used to store set of data of similar data types at contiguous memory locations.
Unlike Arrays, Structures in C++ are user defined data types which are used to store group of items of non-similar data types.

What is a structure?

A structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type.

Structures in C++

How to create a structure?

The ‘struct’ keyword is used to create a structure. The general syntax to create a structure is as shown below:

struct structureName< member1; member2; member3; . . . memberN; >;

Structures in C++ can contain two types of members:

Example:

C++

// Data Members // Member Functions void printDetails()

In the above structure, the data members are three integer variables to store roll number, age and marks of any student and the member function is printDetails() which is printing all of the above details of any student.

How to declare structure variables?

A structure variable can either be declared with structure declaration or as a separate declaration like basic types.

C++

// A variable declaration with structure declaration. struct Point > p1; // The variable p1 is declared with 'Point' // A variable declaration like basic data types struct Point struct Point p1; // The variable p1 is declared like a normal variable

Note: In C++, the struct keyword is optional before in declaration of a variable. In C, it is mandatory.

How to initialize structure members?
Structure members cannot be initialized with declaration. For example the following C program fails in compilation.
But is considered correct in C++11 and above.

C++

struct Point int x = 0; // COMPILER ERROR: cannot initialize members here int y = 0; // COMPILER ERROR: cannot initialize members here

The reason for above error is simple, when a datatype is declared, no memory is allocated for it. Memory is allocated only when variables are created.

Structure members can be initialized with declaration in C++. For Example the following C++ program Executes Successfully without throwing any Error.

C++

// In C++ We can Initialize the Variables with Declaration in Structure. using namespace std; struct Point < int x = 0; // It is Considered as Default Arguments and no Error is Raised struct Point p1; // Accessing members of point p1 // No value is Initialized then the default value is considered. ie x=0 and y=1; // Initializing the value of y = 20; // This code is contributed by Samyak Jain
x=0, y=1 x=0, y=20

Structure members can be initialized using curly braces ‘<>’. For example, following is a valid initialization.

C++

struct Point < // A valid initialization. member x gets value 0 and y // gets value 1. The order of declaration is followed. struct Point p1 = < 0, 1 >;

How to access structure elements?
Structure members are accessed using dot (.) operator.

C++

using namespace std; struct Point < struct Point p1 = < 0, 1 >; // Accessing members of point p1 Output
x = 20, y = 1

What is an array of structures?

Like other primitive data types, we can create an array of structures.

C++

using namespace std; struct Point < // Create an array of structures struct Point arr[10]; // Access array members cout << arr[0].x << " " << arr[0].y; Output
10 20

What is a structure pointer?
Like primitive types, we can have pointer to a structure. If we have a pointer to structure, members are accessed using arrow ( -> ) operator instead of the dot (.) operator.

C++

using namespace std; struct Point < struct Point p1 = < 1, 2 >; // p2 is a pointer to structure p1 struct Point* p2 = &p1; // Accessing structure members using // structure pointer Output

What is structure member alignment?
See https://www.geeksforgeeks.org/structure-member-alignment-padding-and-data-packing/
In C++, a structure is the same as a class except for a few differences. The most important of them is security. A Structure is not secure and cannot hide its implementation details from the end user while a class is secure and can hide its programming and designing details. Learn more about the differences between Structures and Class in C++.

Like Article -->

Please Login to comment.

Similar Reads

Difference Between C Structures and C++ Structures

Let's discuss, what are the differences between structures in C and structures in C++? In C++, structures are similar to classes. Differences Between the C and C++ StructuresC Structures C++ Structures Only data members are allowed, it cannot have member functions.Can hold both: member functions and data members.Cannot have static members.Can have

6 min read Policy based data structures in g++

The g++ compiler also supports some data structures that are not part of the C++ standard library. Such structures are called policy-based data structures. These data structures are designed for high-performance, flexibility, semantic safety, and conformance to the corresponding containers in std.To use these structures, the following lines must be

6 min read Data Structures and Algorithms | Set 36

Que - 1. The function shiftNode() which takes as input two linked lists- destination and source. It deletes front node from source and places it onto the front of destination. Choose the set of statements which replace X, Y, Z in given function. void shiftNode(struct node** destRoot, struct node** srcRoot) < // the front of source node struct node*

4 min read Data Structures and Algorithms | Set 37

Que - 1. For 8 keys and 6 slots in a hashing table with uniform hashing and chaining, what is the expected number of items that hash to a particular location. (A) 2.33 (B) 0.75 (C) 1.33 (D) 2 Solution: Probability that key1 ends up in slot 1 = 1/6 Probability that key2 ends up in slot 1 = 1/6 Probability that key3 ends up in slot x = 1/6 Probabilit

4 min read Slack Bytes in Structures : Explained with Example

Structures: Structures are used to store the data belonging to different data types under the same variable name. An example of a structure is as shown below: struct STUDENT < char[10] name; int id; >; The memory space for the above structure would be allocated as shown below: Here we see that there is no empty spaces in between the members of the

3 min read Control Structures in Programming Languages

Control Structures are just a way to specify flow of control in programs. Any algorithm or program can be more clear and understood if they use self-contained modules called as logic or control structures. It basically analyzes and chooses in which direction a program flows based on certain parameters or conditions. There are three basic types of l

3 min read What are the C programming concepts used as Data Structures

Data Types Data-type in simple terms gives us information about the type of data. Example, integer, character, etc. Data-types in C language are declarations for the variables. Data-types are classified as: Primitive or Built-in data types Some of the examples of primitive data types are as follows Variable named ch refers to the memory address 100

10 min read User Defined Data Structures in Octave

Vectors and matrices are by all account not the only means that Octave offers for gathering information into a single entity. User-defined data structures are likewise accessible that empower the software engineers to make variable types that mix numbers, strings, and arrays. A structure is utilized to speak to data about something more confounded

3 min read Array of Structures vs Array within a Structure in C++

In C++, an array of structure and an array within structure are used frequently used for data storage. Although they sound similar, they work pretty differently from each other. In this article, we will discuss the key differences between an array of structures and an array within structures and clarify the confusion. Array of Structures in C++An a

4 min read Internal Data Structures and Time Complexity Table of All the C++ STL Containers

As we all are using STL quite heavily in our programs in Interviews, Coding Contests. So knowing the Time complexity of the most frequently used operation and the data structure used behind the scene (in the internal implementation of the STL Library) is a must to know information. C++ STL Containers with Time Complexity & Data Structure used B

2 min read C Structures

The structure in C is a user-defined data type that can be used to group items of possibly different types into a single type. The struct keyword is used to define the structure in the C programming language. The items in the structure are called its member and they can be of any valid data type. Additionally, the values of a structure are stored i

10 min read C++ Programming Language

C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr

9 min read 30 OOPs Interview Questions and Answers (2024) Updated

Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,

15+ min read C++ Programming Examples

Writing C++ programs yourself is the best way to learn the C++ language. C++ programs are also asked in the interviews. This article covers the top practice problems for basic C++ programs on topics like control flow, patterns, and functions to complex ones like pointers, arrays, and strings. C++ Tutorial C++ Recent Articles Topics: Basic Programs

9 min read C++ Interview Questions and Answers (2024)

C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent in C++. It is utilized by top IT companies such as

15+ min read vector erase() and clear() in C++

Prerequisite: Vector in C++ Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::clear() The clear() function is used to remove all the elements of the vector container, thus making it size 0. Syntax

6 min read Substring in C++

The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is <string>. The substring function takes two values pos and len as an argument

8 min read 2D Vector In C++ With User Defined Size

A 2D vector is a vector of the vector. Like 2D arrays, we can declare and assign values to a 2D vector! Assuming you are familiar with a normal vector in C++, with the help of an example we demonstrate how a 2D vector differs from a normal vector below: C/C++ Code /* Vectors belong to a C++ library called STL so we need to import it first! */ #incl

8 min read Inheritance in C++

The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the

15+ min read C++ Classes and Objects

In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which holds its own data members and member functions, w

9 min read Decision Making in C (if , if..else, Nested if, if-else-if )

The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making sta

11 min read C++ Data Types

All variables use data type during declaration to restrict the type of data to be stored. Therefore, we can say that data types are used to tell the variables the type of data they can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared. Every data type

10 min read Priority Queue in C++ Standard Template Library (STL)

A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority ). In C++ STL, the top elemen

11 min read Vector in C++ STL

Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse

11 min read Map in C++ Standard Template Library (STL)

Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the <map> header file. Basic std::map Member FunctionsSome basic functions associated with std::

8 min read Object Oriented Programming in C++

Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data

10 min read Operator Overloading in C++

in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning. In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot overload in C++. C++ Operator OverloadingC++ has

8 min read Friend Class and Function in C++

A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node. We can declare a friend class in C++ by using the

6 min read Constructors in C++

Constructor in C++ is a special method that is invoked automatically at the time an object of a class is created. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. It constructs the values i.e. provides data for the object which is why it is known as a constructor

7 min read Bitwise Operators in C

In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. The | (bitwise OR) in C takes two n