Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Structures

The structure is a user-defined data type that is available in C++.


Structures are used to combine different types of data types, just like an array is used to combine
the same type of data types.
A structure is declared by using the keyword “struct“. When we declare a variable of the structure
we need to write the keyword “struct in C language but for C++ the keyword is not mandatory.

Structure using typedef: typedef is a keyword that is used to assign a new name to any existing
data-type. Below is the C++ program illustrating use of struct using typedef:

// C++ program to demonstrate the use


// of struct using typedef
#include <bits/stdc++.h>
using namespace std;

// Declaration of typedef
typedef struct GeekForGeeks {

int G1;
char G2;
float G3;

} GFG;

// Driver Code
int main()
{
GFG Geek;
Geek.G1 = 85;
Geek.G2 = 'G';
Geek.G3 = 989.45;

cout << "The value is : " << Geek.G1 << endl;

cout << "The value is : " << Geek.G2 << endl;

cout << "The value is : " << Geek.G3 << endl;

return 0;
}
Output
The value is : 85
The value is : G
The value is : 989.45

Explanation:

In the above code, the keyword “typedef” is used before struct and after the closing bracket of
structure, “GFG” is written.
Now create structure variables without using the keyword “struct” and the name of the struct.
A structure instance has been created named “Geek” by just writing “GFG” before it.

C++ Unions
In C++, a union is a user-defined datatype in which we can define members of different types of data
types just like structures. But one thing that makes it different from structures is that the member
variables in a union share the same memory location, unlike a structure that allocates memory
separately for each member variable. The size of the union is equal to the size of the largest data type.

Memory space can be used by one member variable at one point in time, which means if we assign
value to one member variable, it will automatically deallocate the other member variable stored in the
memory which will lead to loss of data.

Need of Union in C++


When the available memory is limited, it can be used to achieve memory efficiency.
It is used to encapsulate different types of data members.
It helps in optimizing the performance of applications.
Syntax of Union in C++

union Union_Name {
// Declaration of data members
}; union_variables;

After defining the union we can also create an instance of it the same as we create an object of

int main(){
union Union_Name var1;
// or
Union_Name var1;
}

Enumeration in C++
Enumeration (Enumerated type) is a user-defined data type that can be assigned some limited values.
These values are defined by the programmer at the time of declaring the enumerated type.

If we assign a float value to a character value, then the compiler generates an error. In the same way,
if we try to assign any other value to the enumerated data types, the compiler generates an error.
Enumerator types of values are also known as enumerators.
// C++ Program to Demonstrate the Functioning of Enumerators
// with an Example of Year
#include <bits/stdc++.h>
using namespace std;

// Defining enum Year


enum year {
Jan,
Feb,
Mar,
Apr,
May,
Jun,
Jul,
Aug,
Sep,
Oct,
Nov,
Dec
};

// Driver Code
int main()
{
int i;

// Traversing the year enum


for (i = Jan; i <= Dec; i++)
cout << i << " ";

return 0;
}

typedef in C++
typedef keyword in C++ is used for aliasing existing data types, user-defined data types, and pointers
to a more meaningful name.
Mostly typedefs are used for aliasing, only if the predefined name is too long or complex to write again
and again.
Applications of typedef in C++
typedef in C++ can be used for aliasing predefined data types with long names.
It can be used with STL data structures like Vectors, Strings, Maps, etc.
typedef can be used with arrays as well.
We can use typedef with normal pointers as well as function pointers.

C++ Bit Fields


Bit Field is a feature in C++ for specifying the size of struct and class members so that they occupy a
specific number of bits, not the default memory size.

Bit-Field Syntax in Struct

struct StructName {
dataType fieldName : width;
// more bit-field members...
};

Bit-Field Syntax in Classes

class ClassName {
public:
dataType fieldName : width;
// more bit-field members...
};

Note: It is to be noted that bit fields are only acceptable for integral data types.

Applications of Bit Fields in C++


It is majorly used for memory optimization as it allows us to use only the necessary number of bits
to represent a member variable which reduces memory overhead.
It can be used to compress the data so that it can take less time to transfer data from one point to
another over the network.
It can be used to design hardware registers that have specific bit structures.
In graphics applications, color components, pixel formats, and image data often have specific bit
requirements which can be customized using bit fields.
Differences Between the C and C++ Structures

C Structures C++ Structures

Only data members are allowed, it cannot Can hold both: member functions and data
have member functions. members.

Cannot have static members. Can have static members.

Cannot have a constructor inside a structure. Constructor creation is allowed.

Direct Initialization of data members is not


Direct Initialization of data members is possible.
possible.

Writing the ‘struct’ keyword is necessary to Writing the ‘struct’ keyword is not necessary to
declare structure-type variables. declare structure-type variables.

Do not have access modifiers. Supports access modifiers.

Can have both pointers and references to the


Only pointers to structs are allowed.
struct.

Sizeof operator will generate 0 for an empty Sizeof operator will generate 1 for an empty
structure. structure.

Data Hiding is not possible. Data Hiding is possible.

Self Referential Structures


Self Referential structures are those structures that have one or more pointers which point to the same
type of structure, as their member.
How to declare structure variables?

// A variable declaration with structure declaration.


struct Point
{
int x, y;
} p1; // The variable p1 is declared with 'Point'

// A variable declaration like basic data types


struct Point
{
int x, y;
};

int main()
{
struct Point p1; // The variable p1 is declared like a normal variable
}

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.

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.
// In C++ We can Initialize the Variables with Declaration in Structure.

#include <iostream>
using namespace std;

struct Point {
int x = 0; // It is Considered as Default Arguments and no Error is Raised
int y = 1;
};

int main()
{
struct Point p1;

// Accessing members of point p1


// No value is Initialized then the default value is considered. ie x=0 and y=1;
cout << "x = " << p1.x << ", y = " << p1.y<<endl;

// Initializing the value of y = 20;


p1.y = 20;
cout << "x = " << p1.x << ", y = " << p1.y;
return 0;
}

Output
x=0, y=1
x=0, y=20

Dynamic Memory Allocation in C using malloc(),


calloc(), free() and realloc()

C Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure (like
Array) is changed during the runtime.
There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate dynamic
memory allocation in C programming. They are:
malloc()
calloc()
free()
realloc()

C malloc() method
The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of
memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any
form. It doesn’t Initialize memory at execution time so that it has initialized each block with the default
garbage value initially.

Syntax of malloc() in C
ptr = (cast-type*) malloc(byte-size)

If space is insufficient, allocation fails and returns a NULL pointer.

C calloc() method
“calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of
blocks of memory of the specified type. it is very much similar to malloc() but has two different points
and these are:

It initializes each block with a default value ‘0’.


It has two parameters or arguments as compare to malloc().
Syntax of calloc() in C
ptr = (cast-type*)calloc(n, element-size);
here, n is the no. of elements and element-size is the size of each element.

C free() method
“free” method in C is used to dynamically de-allocate the memory. The memory allocated using
functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used,
whenever the dynamic memory allocation takes place.

Syntax of free() in C
free(ptr);
C realloc() method
“realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a
previously allocated memory. In other words, if the memory previously allocated with the help of malloc
or calloc is insufficient, realloc can be used to dynamically re-allocate memory. re-allocation of memory
maintains the already present value and new blocks will be initialized with the default garbage value.

Syntax of realloc() in C
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.
If space is insufficient, allocation fails and returns a NULL pointer.

new operator
The new operator denotes a request for memory allocation on the Free Store. If sufficient memory is
available, a new operator initializes the memory and returns the address of the newly allocated and
initialized memory to the pointer variable.

Syntax to use new operator

pointer-variable = new data-type;


EG: int *p = new int;

Initialize memory:
pointer-variable = new data-type(value);

Allocate a block of memory:


pointer-variable = new data-type[size];
EG: int *p = new int[10];
Normal Array Declaration vs Using new
The most important difference is, that normal arrays are deallocated by the compiler (If the array is
local, then deallocated when the function returns or completes). However, dynamically allocated arrays
always remain there until either they are deallocated by the programmer or the program terminates.

delete operator
delete pointer-variable: Eg: delete p;
delete[] pointer-variable: Eg: delete[] p;

malloc() vs new():
malloc(): It is a C library function that can also be used in C++, while the “new” operator is specific
for C++ only.
Both malloc() and new are used to allocate the memory dynamically in heap. But “new” does call
the constructor of a class whereas “malloc()” does not.

free() vs delete:
free() is a C library function that can also be used in C++, while “delete” is a C++ keyword.
free() frees memory but doesn’t call Destructor of a class whereas “delete” frees the memory and
also calls the Destructor of the class.

Dot(.) Operator vs Arrow Operator(->)


Feature Dot (.) Operator Arrow (->) Operator

Used with objects or structures Used with pointers to objects or


Usage Context
directly structures

Syntax object.member pointer->member

Dereferencing No automatic dereferencing Automatically dereferences the pointer

Example in C++ object.name objectPtr->name

Direct access to the memory of Access via a pointer, dereferencing it


Memory Access
the object first

Typical Use When you have a direct instance When you have a pointer to an
Case of a structure or class instance of a structure or class
Feature Dot (.) Operator Arrow (->) Operator

Language Common in many OO languages Common in C and C++ for pointer


Context like Java, Python, C++ operations

When to use dot operator and when to use arrow operator ?


Use the dot operator ( . ) with direct instances of structures or classes. Use the arrow operator ( -> )
with pointers to structures or classes to access their members.

Memory leak in C++ and How to avoid it?


Memory leakage occurs in C++ when programmers allocates memory by using new keyword and
forgets to deallocate the memory by using delete() function or delete[] operator.

How to avoid Memory Leak?

Instead of managing memory manually, try to use smart pointers where applicable.
use std::string instead of char *. The std::string class handles all memory management internally,
and it’s fast and well-optimized.
Allocate memory by new keyword and deallocate memory by delete keyword and write all code
between them.

Difference between Static and Dynamic Memory Allocation in C

Static Memory Allocation Dynamic Memory Allocation

In the static memory allocation, variables


In the Dynamic memory allocation, variables get
get allocated permanently, till the program
allocated only if your program unit gets active.
executes or function call finishes.

Static Memory Allocation is done before Dynamic Memory Allocation is done during
program execution. program execution.

It uses stack for managing the static It uses heap for managing the dynamic allocation
allocation of memory. of memory

It is less efficient. It is more efficient

In Dynamic Memory Allocation, there is memory


In Static Memory Allocation, there is no
re-usability and memory can be freed when not
memory re-usability.
required.
Static Memory Allocation Dynamic Memory Allocation

In static memory allocation, once the


In dynamic memory allocation, when memory is
memory is allocated, the memory size can
allocated the memory size can be changed.
not change.

This allows reusing the memory. The user can


In this memory allocation scheme, we allocate more memory when required. Also, the
cannot reuse the unused memory. user can release the memory when the user needs
it.

In this memory allocation scheme,


In this memory allocation scheme, execution is
execution is faster than dynamic memory
slower than static memory allocation.
allocation.

In this memory is allocated at compile time. In this memory is allocated at run time.

In this allocated memory remains from start In this allocated memory can be released at any
to end of the program. time during the program.

Example: This static memory allocation is Example: This dynamic memory allocation is
generally used for array. generally used for linked list.

You might also like