0% found this document useful (0 votes)
3 views95 pages

OOP Notes

The document provides an overview of various concepts in C++ including aliases, addresses, pointers, and dynamic memory allocation. It explains how to use references, pass variables by value or reference, and manage dynamic arrays with functions for allocation, initialization, and deallocation. Additionally, it covers structures in C++, demonstrating how to define and access them, as well as methods for initializing structure instances.

Uploaded by

mehwish.kiran
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views95 pages

OOP Notes

The document provides an overview of various concepts in C++ including aliases, addresses, pointers, and dynamic memory allocation. It explains how to use references, pass variables by value or reference, and manage dynamic arrays with functions for allocation, initialization, and deallocation. Additionally, it covers structures in C++, demonstrating how to define and access them, as well as methods for initializing structure instances.

Uploaded by

mehwish.kiran
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Alias in C++:

An alias in C++ is an alternative name or reference for an existing variable, often


created using references or aliases.
int x = 10;
int& alias = x; // 'alias' is an alias for ‘x’
cout<< alias;
Address in C++:
In C++, the address of a variable is obtained using the address-of operator &, just like in
C.
int y = 20;
cout<< &y; //’&’ is used to print the address of y
Pointer in C++:
In C++, pointers are variables that store memory addresses.
int a = 5;
int* ptr_to_a = &a; // 'ptr_to_a' holds the memory address of 'a'
Dereference in C++:
Dereferencing a pointer or reference in C++ allows you to access the value stored at a
memory location pointed to by a pointer or reference.
int z = 30;
int* pointer_to_z = &z;
int value_of_z = *pointer_to_z; // 'value_of_z' now holds the value 30
*pointer_to_z = 100;
cout<<z;
Pass by Value:

void modifyValue(int x) {
x = 20; // Changes the local copy of 'x'
}
int main() {
int num = 10;
modifyValue(num);
cout << num; // Output: 10 (original 'num' is unchanged)
return 0;
}
Pass by Reference:

void modifyReference(int& x) {
x = 20; // Changes the original 'x'
}
int main() {
int num = 10;
modifyReference(num);
cout << num; // Output: 20 (original 'num' is modified)
return 0;
}
Pass a variable by reference using pointers

void modifyWithPointer(int* x) {
*x = 20; // Changes the original variable pointed to by 'x'
}

int main() {
int num = 10;
modifyWithPointer(&num);
cout << num; // Output: 20 (original 'num' is modified)
return 0;
}
Single Pointer
int Value = 42;
int *singlePtr = &Value;

Double Pointer
int **doublePtr = & singlePtr;

Triple Pointer
int ***triplePtr = & doublePtr;
// Pointer to int // Pointer to char
int intValue = 10; char charValue = 'A';
int *intPtr = &intValue; char *charPtr = &charValue;

cout <<intValue; cout <<charValue;


cout<<*intptr; cout<<*charptr;

// Pointer to int array // Pointer to char array

int intArray[] = {1, 2, 3, 4, 5}; char charArray[] = "Hello";


int *intArrayPtr = intArray; char *charArrayPtr = charArray;

for (int i = 0; i < 5; i++) { for (int i = 0; charArray[i] != '\0'; i++) {


cout <<intArray[i] << endl; cout << charArray[i] <<endl;
} }

for (int i = 0; i < 5; i++) { for (int i = 0; charArrayPtr[i] != '\0'; i++) {


cout<< *(intArrayPtr + i) <<endl; cout << *(charArrayPtr + i) <<endl;
} }
// Pointer to int 2D array
int int2DArray[2][3] = { {1, 2, 3}, {4, 5, 6} };
int(*int2DArrayPtr)[3] = int2DArray;

// Accessing elements using the arrayname & [


// Accessing elements using the arrayname & [ ]
]
for (int i = 0; i < 2; i++) {
for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) {
for (int j = 0; j < 3; j++) { cout << int2DArray[i][j];
cout << int2DArrayPtr[i][j]; }
} cout << endl;
cout << endl; }
} // Accessing elements using arrayname & [ ] &
pointer arithmetic
// Accessing elements using pointer name & [ ]
for (int i = 0; i < 2; i++) {
& pointer arithmetic for (int j = 0; j < 3; j++) {
for (int i = 0; i < 2; i++) { cout << *(int2DArray[i] + j);
for (int j = 0; j < 3; j++) { }
cout << *(int2DArrayPtr[i] + j); cout << endl;
} }
cout << endl; // Accessing elements using pointer arithmetic
for (int i = 0; i < 2; i++) {
}
for (int j = 0; j < 3; j++) {
// Accessing elements using pointer arithmetic cout << *(*(int2DArray + i) + j);
for (int i = 0; i < 2; i++) { }
for (int j = 0; j < 3; j++) { cout << endl;
cout << *(*(int2DArrayPtr + i) + j); }
}
cout << endl;
}
// Pointer to char 2D array
char char2DArray[2][6] = { "Hello", "World" };
char(*char2DArrayPtr)[6] = char2DArray;

// Accessing elements using the pointer // Accessing elements using the array name & [ ]
for (int i = 0; i < 2; i++) { for (int i = 0; i < 2; i++) {
cout << char2DArrayPtr[i] << endl; for (int j = 0; j < 5; j++) {
} cout << char2DArray[i][j] << endl;
}
// Accessing elements using pointer name & [
] & pointer arithmetic // Accessing elements using arrayname & [ ] &
for (int i = 0; i < 2; i++) { pointer arithmetic
for (int j = 0; j < 5; j++) { for (int i = 0; i < 2; i++) {
cout << *(char2DArrayPtr[i] + j); for (int j = 0; j < 5; j++) {
} cout << *(char2DArrayPtr[i] + j);
cout << endl; }
} cout << endl;
}
// Accessing elements using pointer
arithmetic // Accessing elements using pointer arithmetic
for (int i = 0; i < 2; i++) { for (int i = 0; i < 2; i++) {
for (int j = 0; j < 5; j++) { for (int j = 0; j < 5; j++) {
cout << *(*(char2DArrayPtr + i) + j); cout << *(*(char2DArrayPtr + i) + j);
} }
cout << endl; cout << endl;
} }
Pointers Array
int arr1[] = {1, 2, 3};
int arr2[] = {4, 5, 6};
int arr3[] = {7, 8, 9};

int *ptrArray[] = {arr1, arr2, arr3};

// Example of using the pointer array // Example of using pointer notation to print
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) { for (int j = 0; j < 3; j++) {
cout << ptrArray[i][j] << " "; cout<< *(*(ptrArray + i) + j) << " ";
} }
cout << endl; cout << std::endl;
} }

*(*(ptrArray+i)+j) is equivalent to
ptrArray[i][j]
// DMA 1D int array Allocate and initialize a dynamic
int *dma1DArray = new int[5]; 1D integer array using a loop
dma1DArray[0] = 10;
dma1DArray[1] = 20; int main() {
dma1DArray[2] = 30; int size = 5;
dma1DArray[3] = 40; int *dma1DArray = new int[size];
dma1DArray[4] = 50;
delete[] dma1DArray; for (int i = 0; i < size; i++) {
dma1DArray[i] = (i + 1) * 10;
}

// Print the array elements


for (int i = 0; i < size; i++) {
cout << dma1DArray[i] << endl;
}

// Deallocate the memory


delete[] dma1DArray;

return 0;
}
// DMA 2D int array allocate, initialize, and deallocate a dynamic 2D
int **dma2DArray = new int *[2]; integer array using loops
dma2DArray[0] = new int[3]; int main() {
dma2DArray[1] = new int[3]; int rows = 2; int cols = 3;
dma2DArray[0][0] = 1; int **dma2DArray = new int *[rows];
dma2DArray[0][1] = 2; for (int i = 0; i < rows; i++) {
dma2DArray[0][2] = 3; dma2DArray[i] = new int[cols];
dma2DArray[1][0] = 4; }
dma2DArray[1][1] = 5;
dma2DArray[1][2] = 6; int value = 1;
delete[] dma2DArray[0]; for (int i = 0; i < rows; i++) {
delete[] dma2DArray[1]; for (int j = 0; j < cols; j++) {
delete[] dma2DArray; dma2DArray[i][j] = value;
value++;
}
}

// Deallocate the memory


for (int i = 0; i < rows; i++) {
delete[] dma2DArray[i];
}
delete[] dma2DArray;
// Function that returns a pointer to an integer
int* returnPointer() {
int* ptr = new int(42);
return ptr;
}
// Function that takes a pointer as an argument and modifies its value
void modifyValue(int* ptr) {
*ptr = 100;
}

int main() {
// Function returning a pointer
int* ptr1 = returnPointer();
cout << "Value returned by function: " << *ptr1 << endl;
delete ptr1;

// Function taking a pointer as an argument


int value = 10;
int* ptr2 = &value;
modifyValue(ptr2);
cout << "Modified value in main: " << value << endl;

return 0;
}
// Swap values using pointers
int x = 5;
int y = 7;
int* xPtr = &x;
int* yPtr = &y;

int* temp = xPtr;


xPtr = yPtr;
yPtr = temp;

cout << "Swapped values: x = " << *xPtr << ", y = " << *yPtr << endl;
Encapsulate the allocation, initialization, printing, and deallocation of dynamic arrays
into functions for better code organization

int main() {

//allocation, initialization
int* dma1DArray = createAndInitialize1DArray(5);
int** dma2DArray = createAndInitialize2DArray(2, 3);

//printing
print1DArray(dma1DArray, 5);
print2DArray(dma2DArray, 2, 3);

//deallocation
delete1DArray(dma1DArray);
delete2DArray(dma2DArray, 2);

return 0;
}
// Function to allocate and initialize a 1D dynamic array
int* createAndInitialize1DArray(int size) {
int* array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = (i + 1) * 10;
}
return array;
}

// Function to allocate and initialize a 2D dynamic array


int** createAndInitialize2DArray(int rows, int cols) {
int** array = new int*[rows];
for (int i = 0; i < rows; i++) {
array[i] = new int[cols];
for (int j = 0; j < cols; j++) {
array[i][j] = (i * cols) + j + 1;
}
}
return array;
}
// Function to print a 1D dynamic array
void print1DArray(int* array, int size) {
cout << "DMA 1D Array: ";
for (int i = 0; i < size; i++) {
cout << array[i] << " ";
}
cout << endl;
}

// Function to print a 2D dynamic array


void print2DArray(int** array, int rows, int cols) {
cout << "DMA 2D Array:" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << array[i][j] << " ";
}
cout <<endl;
}
}
// Function to deallocate memory for a 1D dynamic array
void delete1DArray(int* array) {
delete[] array;
}

// Function to deallocate memory for a 2D dynamic array


void delete2DArray(int** array, int rows) {
for (int i = 0; i < rows; i++) {
delete[] array[i];
}
delete[] array;
}
Structures in C++
▪ In C++, a structure (struct) is a user-defined data type that allows grouping
multiple variables of different types under one name.

▪ Structures are useful for defining complex data types that represent real-
world entities, such as a Student, Car, or Book.

▪ A structure is declared using the struct keyword. It can contain variables


(members) of different data types.

Syntax:
struct StructureName {
data_type member1;
data_type member2;
...
};
Example:
struct Student {
string name;
int age;
float marks;
};
This structure defines a Student with three
attributes: name, age, and marks.
Example:
struct Student {
string name;
int age;

3. Defining and Accessing Structure float marks;


Members };
Once a structure is declared, we can int main() {
create variables (instances) of that // Creating a structure variable
structure and access its members using Student s1;
the dot (.) operator.
// Assigning values
[Link] = "Ali";
[Link] = 20;
[Link] = 85.5;
// Accessing and displaying values
cout << "Name: " << [Link] << endl;
cout << "Age: " << [Link] << endl;
cout << "Marks: " << [Link] << endl;
return 0;
}
4. Initializing Structures
We can initialize a structure in different ways.
Method 1: Using Direct Assignment
Student s1 = {"Ali", 20, 85.5};
Method 2: Assigning Values After Declaration
Student s2;
[Link] = "Bilal";
[Link] = 22;
[Link] = 90.2;
Method 3: Using Constructor (Inside Struct)
In C++, structures can have constructors.

struct Student { int main() {


string name; Student s3(“haris", 21, 88.0);
int age; cout << "Name: " << [Link] << endl;
float marks; cout << "Age: " << [Link] << endl;
// Constructor (Function) cout << "Marks: " << [Link] << endl;
Student(string n, int a, float m) { return 0;
name = n; }
age = a;
marks = m;
}
};
5. Array of Structures
We can create an array of structures to
store multiple records.
Example:
struct Student { int main() {
string name; Student students[2] = { {"Ali", 20, 85.5}, {"Bilal", 22, 90.2} };

int age;
for (int i = 0; i < 2; i++) {
float marks;
cout << "Student " << i+1 << ": " << students[i].name
};
<< ", Age: " << students[i].age
<< ", Marks: " << students[i].marks << endl;
}
return 0;
}
6. Pointer to Structure
We can use pointers to access structure members.
Example:
struct Student { int main() {
string name; Student s1 = {"Ali", 20, 85.5};
int age; Student* ptr = &s1;
float marks;
}; // Accessing structure members using pointer
cout << "Name: " << ptr->name << endl;
cout << "Age: " << ptr->age << endl;
cout << "Marks: " << ptr->marks << endl;

return 0;
}
Here, ptr->name is the same as (*ptr).name.
7. Structure Object Inside Structure
A structure can contain another structure Object.
Example:
struct Address {
string city;
int zip; int main() {
}; Student s1 = {"Ali", 20, {"New City", 10001}};

struct Student { cout << "Name: " << [Link] << endl;
string name; cout << "City: " << [Link] << endl;
int age; cout << "ZIP: " << [Link] << endl;
Address address;
}; return 0;
}
8. Structure with Functions
Functions can be used inside and outside structures.
Example 1: Function Inside Struct
struct Student {
string name;
int age;
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};

int main() {
Student s1 = {"Ali", 20};
[Link]();
return 0;
}
Example 2: Passing Structure to Function
struct Student {
string name;
int age;
};

void display(Student s) {
cout << "Name: " << [Link] << ", Age: " << [Link] << endl;
}

int main() {
Student s1 = {"Ali", 20};
display(s1);
return 0;
}
1. Pointer Inside a Structure
A structure can contain a pointer as a member, which allows it to reference
dynamically allocated memory or other structures.
Example: Pointer Inside Structure
struct Student { int main() {
string name; Student s1;
int* age; // Pointer to an integer int a = 20;
}; [Link] = "Ali";
[Link] = &a; // Assigning address of a

cout << "Name: " << [Link] << endl;


cout << "Age: " << *([Link]) << endl; //
Dereferencing pointer

return 0;
}
Basic structure using the struct keyword.

// Define a structure int main() {


// Create an instance of the "Person" structure
named "Person" Person person1;
struct Person {
string name; // Assign values to the structure members
int age; [Link] = “Ali";
[Link] = 30;
double height; [Link] = 6.0;
char gender; [Link] = 'M';
};
// Display the information
cout << "Name: " << [Link] << endl;
cout << "Age: " << [Link] << endl;
cout << "Height: " << [Link] << " feet" << endl;
cout << "Gender: " << [Link] << endl;

return 0;
}
Basic structure using the struct keyword.

// Define a int main() {


structure named // Create an instance of the "Point" structure
"Point" for 2D Point p1;
coordinates
// Assign values to the structure members
struct Point { p1.x = 3.5;
double x; p1.y = 2.0;
double y;
}; // Display the coordinates
cout << "Point coordinates: (" << p1.x << ", " << p1.y << ")" << endl;

return 0;
}
Example of a C++ program with a structure containing an array as a member:

// Define a struct named int main() {


"Student" that contains an // Create an instance of the "Student" struct
array of exam scores Student student1;

// Assign values to the structure members


struct Student { [Link] = "Ali";
string name; [Link] = 101;
int rollNumber; [Link][0] = 85;
int examScores[3]; // Array [Link][1] = 92;
to store exam scores for [Link][2] = 78;
three exams
}; // Display the student's information and exam scores
cout << "Name: " << [Link] << endl;
cout << "Roll Number: " << [Link] << endl;
cout << "Exam Scores: ";
for (int i = 0; i < 3; i++) {
cout << [Link][i] << " ";
}
cout << endl;

return 0;
}
Example of a C++ structure with an array of structures:
int main() {
// Create an array of "Student" structures
// Define a structure named const int numStudents = 3; // Number of students
"Student" to represent Student students[numStudents];
student information
// Assign values to the structure members for each student
struct Student { students[0].name = "Ali";
string name; students[0].rollNumber = 101;
int rollNumber;
}; students[1].name = "Bilal";
students[1].rollNumber = 102;
students[2].name = “Usman";
students[2].rollNumber = 103;
// Display the information for each student in the array
for (int i = 0; i < numStudents; i++) {
cout << "Student " << i + 1 << " Information:" << endl;
cout << "Name: " << students[i].name << endl;
cout << "Roll Number: " << students[i].rollNumber << endl;
cout << endl;
}
return 0;
}
Example of a C++ program with a nested struct.

// Define a struct named "Address" int main() {


for storing address information // Create an instance of the "Person" struct
Person person1;
struct Address {
// Assign values to the structure members
string street; [Link] = “Ali";
string city; [Link] = 30;
string state; [Link] = "123 Main St";
string zipCode; [Link] = "Anytown";
}; [Link] = "Capital";
[Link] = "12345";
// Define a struct named "Person"
// Display the person's information, including the nested "Address" struct
that includes the "Address" struct as
cout << "Name: " << [Link] << endl;
a member cout << "Age: " << [Link] << endl;
cout << "Address:" << endl;
struct Person { cout << "Street: " << [Link] << endl;
string name; cout << "City: " << [Link] << endl;
int age; cout << "State: " << [Link] << endl;
Address address; cout << "Zip Code: " << [Link] << endl;
};
return 0;
}
Passing Structure Members as Arguments to Functions:
You can pass individual members of a structure as arguments to a function. For
example:

struct Point {
int x;
int y;
};

void printCoordinates(int x, int y) {


cout << "X: " << x << ", Y: " << y << endl;
}

Point myPoint = {5, 10};

printCoordinates(myPoint.x, myPoint.y);
Passing Structure Variables (object) as Parameters:
You can pass entire structure variables as function parameters:

void printPoint(Point p) {
cout << "X: " << p.x << ", Y: " << p.y << endl;
}

Point myPoint = {5, 10};

printPoint(myPoint);
Returning Structure from Function:
Functions can return structures as well:

Point createPoint(int x, int y) {


Point p;
p.x = x;
p.y = y;
return p;
}

Point newPoint = createPoint(3, 7);


Pointers to Structure Variables:
You can use pointers to access and manipulate
structure variables:

Point myPoint = {5, 10};

Point* pPoint = &myPoint;

cout << "X: " << pPoint->x << ", Y: " << pPoint-
>y << endl;
Passing Structure Pointers as Arguments to a Function:
You can pass pointers to structures as function parameters:

void modifyPoint(Point* p) {
p->x += 2;
p->y += 2;
}

Point myPoint = {5, 10};

modifyPoint(&myPoint);
Returning a Structure Pointer from Function:
Functions can also return pointers to structures:

Point* createAndReturnPoint(int x, int y) {


Point* p = new Point;
p->x = x;
p->y = y;
return p;
}
Point* newPoint = createAndReturnPoint(3, 7);

new Point allocates memory on the heap (free store). Heap memory does NOT go out
of scope when the function ends. Only the pointer variable p goes out of scope, not
the object it points to. The returned pointer still points to valid memory.

Point* createAndReturnPoint(int x, int y) {


Point p; // stack memory
p.x = x;
p.y = y;
return &p; // Not allowed, returning address of local variable
}
struct Point {
int x, y;
};
Point* createAndReturnPoint(int x, int y) {
Point* p = new Point;
p->x = x;
p->y = y;
return p;
}

int main() {
Point* newPoint = createAndReturnPoint(3, 7);

cout << "Point: (" << newPoint->x << ", " << newPoint->y << ")\n";

// Free allocated memory


delete newPoint;

return 0;
}
Passing Array of Structures:
You can create an array of structures and pass them to functions:

struct Student {
string name;
int age;
};

void printStudents(Student students[], int size) {


for (int i = 0; i < size; i++) {
cout << "Name: " << students[i].name << ", Age: " << students[i].age << endl;
}
}

Student classStudents[3] = {{"Ali", 20}, {"Bilal", 22}, {“Usman", 19}};

printStudents(classStudents, 3);
Dynamic allocation within a struct typically involves allocating memory for one or
more members of the struct using pointers. This is commonly used when you need
to handle variable-sized data or when you want to manage memory manually.

// Define a struct named int main() {


// Create an instance of the "Student" struct
"Student" that includes Student student1;
dynamic memory allocation
// Allocate memory for the name member dynamically
[Link] = new char[50]; // Allocates space for a name of up to 49 characters
struct Student { // Assign values to the structure members
// Dynamic memory allocation for cout << "Enter Name: ";
name [Link]([Link], 50);
char* name;
cout << "Enter Roll Number: ";
int rollNumber; cin >> [Link];
}; // Display the student's information
cout << "Name: " << [Link] << endl;
cout << "Roll Number: " << [Link] << endl;

// Don't forget to release the allocated memory when you're done


delete[] [Link];

return 0;
}
Dynamic allocation of a 2D array within a struct involves using
pointers to create a dynamically allocated 2D array and then
storing a pointer to this array as a member of the struct.

// Define a struct named // Function to allocate memory for a dynamic 2D array


"Matrix" to store a dynamic int** createDynamic2DArray(int rows, int cols) {
2D array int** array = new int*[rows]; // Allocate memory for an array of int
pointers (rows)
for (int i = 0; i < rows; i++) {
struct Matrix { array[i] = new int[cols]; // Allocate memory for each row (cols)
// Pointer to a dynamically allocated }
2D array return array;
}
int** data;

int rows; // Function to deallocate memory for a dynamic 2D array


int cols; void deleteDynamic2DArray(int** array, int rows) {
}; for (int i = 0; i < rows; i++) {
delete[] array[i]; // Deallocate memory for each row
}
delete[] array; // Deallocate memory for the array of int pointers
}
int main() { // Display the matrix
// Create an instance of the "Matrix" struct cout << "Matrix:" << endl;
Matrix matrix1; for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < [Link]; j++) {
// Input the number of rows and columns
cout << [Link][i][j] << " ";
cout << "Enter the number of rows: ";
cin >> [Link]; }
cout << "Enter the number of columns: "; cout << endl;
cin >> [Link]; }

// Allocate memory for the dynamic 2D array


[Link] = createDynamic2DArray([Link], [Link]);
// Deallocate memory when you're done
// Input data into the matrix
deleteDynamic2DArray([Link], [Link]);
cout << "Enter matrix elements:" << endl;
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < [Link]; j++) { return 0;
cin >> [Link][i][j]; }
}
}
Dynamic Memory Allocation (DMA) is a technique in C++ that allows you to allocate
memory for variables at runtime from the heap memory. When dealing with structures,
you can dynamically allocate memory for structure variables using pointers.

// Define a int main() {


structure // Dynamically allocate memory for a single structure variable
Student* studentPtr = new Student;
struct Student
{ // Initialize the dynamically allocated structure
string name; studentPtr->name = "Ali";
int age; studentPtr->age = 20;
};
// Access and print the data
cout << "Name: " << studentPtr->name << ", Age: " << studentPtr->age << endl;

// Don't forget to deallocate the memory when done


delete studentPtr;
// Dynamically allocate memory for an array of structure variables
int numStudents = 3;
Student* studentArray = new Student[numStudents];

// Initialize the dynamically allocated array


studentArray[0] = {"Bilal", 22};
studentArray[1] = {“Usman", 19};
studentArray[2] = {“Hasan", 21};

// Access and print the data in the array


for (int i = 0; i < numStudents; i++) {
cout << "Name: " << studentArray[i].name << ", Age: " << studentArray[i].age << endl;
}

// Don't forget to deallocate the memory when done


delete[] studentArray;

return 0;
}
Functions within structures
struct Person { int main()
string name; {
int age; // Create a Person object
double height;
Person person1;
// Member function to initialize a Person object
// Call the initialize function to set the values
void initialize(const string& n, int a, double h) {
name = n; [Link]("Junaid", 30, 6.1);
age = a;
height = h; // Call the display function to show information
}
[Link]();
// Member function to display information about the person
return 0;
void display() { }
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Height: " << height << endl;
}
};
Functions within structures
struct Rectangle { int main() {
double length; // Create a Rectangle object
double width;

// Member function to calculate the area of the rectangle Rectangle myRectangle;


double calculateArea() {
return length * width; // Set the dimensions of the
} rectangle
// Member function to calculate the perimeter of the rectangle
double calculatePerimeter() { [Link] = 5.0;
return 2 * (length + width); [Link] = 3.0;
}
// Display information about the
// Member function to display information about the rectangle
rectangle
void displayInfo() {
cout << "Length: " << length << endl;
cout << "Width: " << width << endl; [Link]();
cout << "Area: " << calculateArea() << endl;
cout<<"Perimeter:" <<calculatePerimeter()<<endl; return 0;
} }
};
Functions within structures
struct Rectangle { int main() {
double length;
double width; // Create a Rectangle object
// Function prototypes inside the structure
double calculateArea(); Rectangle myRectangle;
double calculatePerimeter();
void displayInfo(); // Set the dimensions of the rectangle
};
[Link] = 5.0;
// Function to calculate the area of a rectangle given a Rectangle object
[Link] = 3.0;
double Rectangle::calculateArea() {
return length * width;
} // Display information about the rectangle using the
// Function to calculate the perimeter of a rectangle given a Rectangle object functions
double Rectangle::calculatePerimeter() {
return 2 * (length + width); [Link]();
}
// Function to display information about a rectangle given a Rectangle object
void Rectangle::displayInfo() { return 0;
cout << "Length: " << length << endl; }
cout << "Width: " << width << endl;
cout << "Area: " << calculateArea() << endl;
cout << "Perimeter: " << calculatePerimeter() << endl;
}
cout << "Enter Major: ";
[Link]([Link], sizeof([Link]));

cout << "Enter Birthdate (day month year): ";


cin >> [Link];
cin >> [Link];
cin >> [Link];

cout << "Enter Registration Date (day month year): ";


cin >> CSStudent.registration_date.day;
cin >> CSStudent.registration_date.month;
cin >> CSStudent.registration_date.year;
#include <iostream>
using namespace std;

struct Student {
string name;
int age;
float gpa;
};

Passing Structure to Function (normal argument)

void show(Student s) {
cout << [Link] << " " << [Link] << endl;
}

Call:
Student s1 = {"Ali", 20, 3.5};
show(s1);
#include <iostream>
using namespace std;

struct Student {
string name;
int age;
float gpa;
};

Passing Structure Members as Arguments

void showMembers(string name, int age) {


cout << name << " " << age << endl;
}

Call:
Student s1 = {"Ali", 20, 3.5};
showMembers([Link], [Link]);
#include <iostream>
using namespace std;

struct Student {
string name;
int age;
float gpa;
};

Passing Structure by Value

void updateByValue(Student s) {
[Link] = 25; // does NOT change original
}

Call:
Student s1 = {"Ali", 20, 3.5};
updateByValue(s1);
#include <iostream>
using namespace std;

struct Student {
string name;
int age;
float gpa;
};

Passing Structure by Reference

void updateByReference(Student &s) {


[Link] = 30; // changes original
}

Call:
Student s1 = {"Ali", 20, 3.5};
updateByReference(s1);

Call by Value vs Reference


cout << [Link] << endl; // see difference after each call
#include <iostream>
using namespace std;

struct Student {
string name;
int age;
float gpa;
};

Passing Structure Pointer as Argument

void updateByPointer(Student *s) {


s->age = 35;
}

Call:
Student s1 = {"Ali", 20, 3.5};
updateByPointer(&s1);
cout << [Link] << endl; // see difference after each call
#include <iostream>
using namespace std;

struct Student {
string name;
int age;
float gpa;
};

Passing Array of Structures to Function

void printStudents(Student arr[], int size) {


for(int i = 0; i < size; i++)
cout << arr[i].name << endl;
}
Call:
Student arr[2] = {{"Ali",20,3.5}, {"Sara",22,3.9}};
printStudents(arr, 2);
#include <iostream>
using namespace std;

struct Student {
string name;
int age;
float gpa;
};

Returning Structure from Function

Student createStudent() {
Student s = {"John", 23, 3.2};
return s;
}
Call:
Student s2 = createStudent();
cout << [Link] << endl;
#include <iostream>
using namespace std;

struct Student {
string name;
int age;
float gpa;
};

Returning Structure Pointer from Function

Student* createStudentPtr() {
Student* s = new Student{"Mike", 24, 3.1};
return s;
}
Call:
Student* ptr = createStudentPtr();
cout << ptr->name << endl;
delete ptr; // free memory
#include <iostream>
using namespace std;

struct Student {
string name;
int age;
float gpa;
};

Input Function (Reading members)

void inputStudent(Student &s) {


cin >> [Link] >> [Link] >> [Link];
}

Call:
Student s3;
inputStudent(s3);
#include <iostream>
using namespace std;

struct Student {
string name;
int age;
float gpa;
};

Display Function

void displayStudent(const Student &s) {


cout << [Link] << " " << [Link] << " " << [Link] << endl;
}

Call:
displayStudent(s3);
#include <iostream>
using namespace std;

struct Student {
string name;
int age;
float gpa;
};

Structure Assignment and Copying

Student a = {"Ali",20,3.5};
Student b;
b = a; // assignment

Direct Copying
Student c = a; // copy at initialization
Shallow Copy Deep Copy

struct Person { Person p3;


string name; [Link] = [Link];
int *age; [Link] = new int;
}; *[Link] = *[Link];

int main() { cout << *[Link] << endl;


Person p1; delete [Link];
int x = 20;
[Link] = "Ali";
[Link] = &x;

Person p2 = p1; // shallow copy

cout << *[Link] << endl;


}
#include <iostream>
using namespace std;

struct Student {
string name;
int age;
float gpa;
};

Constant Structures

Declaring Constant Structure


const Student s4 = {"Sara",22,3.9};
// [Link] = 30; //Not allowed
#include <iostream>
using namespace std;

struct Student {
string name;
int age;
float gpa;
};

Const with Pointer to Structure

Pointer to const

const Student *ptr1 = &s1;


// ptr1->age = 40; //Not allowed
#include <iostream>
using namespace std;

struct Student {
string name;
int age;
float gpa;
};

Const with Pointer to Structure

Const pointer
Student s5 = {"Tom",21,3.4};
Student *const ptr2 = &s5;
ptr2->age = 50; // allowed
// ptr2 = &s1; // Not allowed
#include <iostream>
using namespace std;

struct Student {
string name;
int age;
float gpa;
};

Const with Pointer to Structure

Const pointer
Student s5 = {"Tom",21,3.4};
Student *const ptr2 = &s5;
ptr2->age = 50; // allowed
// ptr2 = &s1; // Not allowed
DMA (Dynamic Memory Allocation) examples in C++ using structures

#include <iostream>
using namespace std;

struct Student {
string name;
int age;
};

Single Object DMA

Allocate
Student *ptr = new Student;
Assign Values
ptr->name = "Ali";
ptr->age = 20;
Display
cout << ptr->name << " " << ptr->age << endl;
Free Memory
delete ptr;
DMA (Dynamic Memory Allocation) examples in C++ using structures

#include <iostream>
using namespace std;

struct Student {
string name;
int age;
};
1D DMA – Array of Structures
Allocate Array
int n = 3;
Student *arr = new Student[n];
Assign Values
for(int i = 0; i < n; i++) {
arr[i].name = "Student";
arr[i].age = 18 + i;
}
Display
for(int i = 0; i < n; i++) {
cout << arr[i].name << " " << arr[i].age << endl;
}
Free Memory
delete[] arr;
DMA (Dynamic Memory Allocation) examples in C++ using structures

#include <iostream>
using namespace std;

struct Student {
string name;
int age;
};
2D DMA – Array of Structure Arrays
Allocate 2D Array Display
int rows = 2, cols = 2; for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
Student **arr = new Student*[rows]; cout << arr[i][j].name << " "
<< arr[i][j].age << " ";
for(int i = 0; i < rows; i++) { }
arr[i] = new Student[cols];
cout << endl;
}
Assign Values }
for(int i = 0; i < rows; i++) { Free Memory
for(int j = 0; j < cols; j++) { for(int i = 0; i < rows; i++) {
arr[i][j].name = "S"; delete[] arr[i];
arr[i][j].age = 20 + i + j; }
} delete[] arr;
}
1. Create a student structure, whose members are
i. Name (a char array),
ii. roll_number,
iii. marks (an array of type float having size 5),
iv. major (a char array, to show the major of the student).
2. There shall also be a nested structure of type date struct inside
the student structure, for the birthdate and registration date.
3. Now first create a student variable named CSStudent.
4. Fill up all the fields (members) with some random values from
the console using “cin”
5. Secondly create another student variable named EEStudent.
6. Assign CSStudent to EEStudent.
7. Show the values of the members of both struct variables using
cout.
#include <iostream>
using namespace std;

// Define a structure for representing dates


struct Date {
int day;
int month;
int year;
};

// Define a structure named "Student"


struct Student {
char name[50];
int roll_number;
float marks[5];
char major[50];
Date birthdate;
Date registration_date;
};
int main() {
// Create a variable named "CSStudent" of type "Student"
Student CSStudent;

// Input values for CSStudent from the console using "cin"


cout << "Enter Name: ";
[Link]([Link], sizeof([Link]));

cout << "Enter Roll Number: ";


cin >> CSStudent.roll_number;

cout << "Enter Marks for 5 Subjects: ";


for (int i = 0; i < 5; i++) {
cin >> [Link][i];
}

[Link](); // Ignore the newline character left in the input buffer


// Create another student variable named "EEStudent" and assign CSStudent to it
Student EEStudent = CSStudent;

// Display the values of CSStudent and EEStudent


cout << "\nValues of CSStudent:" << endl;
cout << "Name: " << [Link] << endl;
cout << "Roll Number: " << CSStudent.roll_number << endl;
cout << "Marks: ";
for (int i = 0; i < 5; i++) {
cout << [Link][i] << " ";
}
cout << endl;
cout << "Major: " << [Link] << endl;
cout << "Birthdate: " << [Link] << "/" <<
[Link] << "/" << [Link] << endl;
cout << "Registration Date: " << CSStudent.registration_date.day << "/" <<
CSStudent.registration_date.month << "/" << CSStudent.registration_date.year <<
endl;
cout << "\nValues of EEStudent (assigned from CSStudent):" << endl;
cout << "Name: " << [Link] << endl;
cout << "Roll Number: " << EEStudent.roll_number << endl;
cout << "Marks: ";
for (int i = 0; i < 5; i++) {
cout << [Link][i] << " ";
}
cout << endl;
cout << "Major: " << [Link] << endl;
cout << "Birthdate: " << [Link] << "/" <<
[Link] << "/" << [Link] << endl;
cout << "Registration Date: " << EEStudent.registration_date.day << "/" <<
EEStudent.registration_date.month << "/" << EEStudent.registration_date.year <<
endl;

return 0;
}
Topic Syntax Key Point Function Call
Define Structure struct S { int a; }; Groups different data types S s1;
Access Member s1.a Use . with object —
Access via Pointer ptr->a Use -> with pointer —
Pass by Value void f(S s); Copy created f(s1);
Pass by Reference void f(S &s); No copy, original changes f(s1);
Pass by Pointer void f(S *s); Use -> inside f(&s1);
Pass Members f(s.a); Only selected values sent f(s1.a);

Array of Structures void f(S arr[], int n); Pass array name f(arr, n);

Return Structure S f(){ return s; } Returns full object S s2 = f();

Return Pointer S* f(){ return new S; } Must delete memory S* p = f();

Input Function void input(S &s); Use reference input(s1);

Display Function void show(const S &s); Use const reference show(s1);


Feature By Value By Reference
Copy Created Yes No
Original Modified No Yes
Memory Usage More Less
Speed Slower Faster

Type Syntax Result


Assignment s2 = s1; Copies all members
Direct Copy S s2 = s1; Copy at initialization
Shallow Copy p2 = p1; Pointer address copied
Deep Copy Allocate new memory Separate memory created

Type Syntax What is Constant?


Const Object const S s; Data cannot change
Pointer to Const const S *ptr; Data fixed, pointer can change
Const Pointer S *const ptr; Pointer fixed, data can change

Type Allocation Deallocation


Single Object new Student delete ptr
1D Array new Student[n] delete[] arr
new Student*[r] + new Delete rows first, then main
2D Array
Student[c] pointer
▪ Define and Print a Structure:
Write a C++ program to define a struct Student with members name, age, and grade. Create an instance and print its values.

▪ User Input in Structure:


Modify the previous program to take input from the user and display the details of a student.

▪ Array of Structures:
Create an array of struct Book containing title, author, and price. Store details of 3 books and display them.

▪ Function with Structure Argument:


Write a function that takes a struct Rectangle with length and width as arguments and returns the area.

▪ Structure with Default Values:


Define a structure Car with brand, model, and year. Initialize it using default values inside main().

▪ Pass Structure by Reference:


Create a struct Employee with name, salary, and designation. Write a function that modifies the salary by reference.

▪ Nested Structures:
Define a structure Address inside struct Employee. Store city and state within Address. Create an employee instance and print its
details.

▪ Pointer to Structure:
Create a pointer to a struct Student, dynamically allocate memory, assign values, and display them.

▪ Structure with Array Member:


Define struct Exam containing subject[3] and marks[3]. Store three subjects and marks for a student, then print them.

▪ Dynamic Array of Structures:


Write a program to dynamically allocate an array of struct Employee, take user input for multiple employees, and print their
details.

▪ Structure and Sorting:


Define struct Student with name and marks. Store details of five students in an array and sort them in descending order of marks.
Scenario: You are designing a mini student management system.
Task:
▪ Create a Student structure with name, rollNo, age, gpa.
▪ Input details for 5 students and display them.
▪ Dynamically allocate memory for the student array.
Hints:
▪ Use 1D DMA for the array.
▪ Use inputStudent() and displayStudent() functions.
▪ Don’t forget delete[] at the end.
Scenario: A library wants to store information about books.
Task:
▪ Create a Book structure: title, author, price,
availableCopies.
▪ Dynamically create a 2D array for 3 shelves × 4 books per shelf.
▪ Assign values to each book and display them neatly.
Hints:
▪ Use 2D DMA (Book** books).
▪ Use nested loops for assignment and printing.
▪ Delete memory in reverse order.
Scenario: You are maintaining employee records.
Task:
▪ Structure Employee: name, id, basicSalary, department.
▪ Input data for 3 employees using functions.
▪ Update salary for a particular employee by passing structure by reference.
▪ Display all employee details.
Hints:
▪ Pass the structure pointer or reference for updating salary.
▪ Include functions inputEmployee(), displayEmployee(),
updateSalary().
Scenario: A shop wants to track inventory.
Task:
▪ Structure Product: name, price, quantity.
▪ Dynamically allocate an array of n products (n input by user).
▪ Input product details.
▪ Find the product with highest price and display it.
Hints:
▪ Use 1D DMA.
▪ Loop through array to find maximum price.
Scenario: Cinema wants to track seat bookings.
Task:
▪ Structure Seat: seatNumber, row, isBooked.
▪ Dynamically create a 2D array for 5 rows × 10 seats per row.
▪ Mark some seats as booked.
▪ Display available and booked seats.
Hints:
▪ Use 2D DMA (Seat** seats).
▪ Use nested loops to mark and display.
Scenario: You want a temporary storage for visitors entering a building.
Task:
▪ Structure Visitor: name, purpose, arrivalTime.
▪ Dynamically allocate memory for visitors as they enter (unknown total
number).
▪ When a visitor leaves, free the memory for that visitor.
Hints:
▪ Use new Visitor for each visitor.
▪ Use delete ptr when visitor leaves.
▪ This simulates dynamic single object DMA.
Scenario: Hospital wants to store patient records.
Task:
▪ Structure Patient: name, age, disease, roomNo.
▪ Dynamically allocate a 1D array of patients.
▪ Update room number of a patient using pointer to structure.
▪ Display all patients in a formatted table.
Hints:
▪ Pass pointer to structure to update room number.
▪ Use loops to display records.
Scenario: Hospital wants to store patient records.
Task:
▪ Structure Patient: name, age, disease, roomNo.
▪ Dynamically allocate a 1D array of patients.
▪ Update room number of a patient using pointer to structure.
▪ Display all patients in a formatted table.
Hints:
▪ Pass pointer to structure to update room number.
▪ Use loops to display records.
#include <iostream>
#include <string>
using namespace std;

// -----------------------------
// Student Database
// -----------------------------
struct Student {
string name;
int rollNo;
int age;
float gpa;
};

void inputStudent(Student &s) {


cout << "Enter name, rollNo, age, gpa: ";
cin >> [Link] >> [Link] >> [Link] >> [Link];
}

void displayStudent(const Student &s) {


cout << [Link] << " " << [Link] << " " <<
[Link] << " " << [Link] << endl;
}
// -----------------------------
// Library Book Records
// -----------------------------
struct Book {
string title;
string author;
float price;
int availableCopies;
};

void inputBook(Book &b) {


cout << "Enter title, author, price, available
copies: ";
cin >> [Link] >> [Link] >> [Link] >>
[Link];
}

void displayBook(const Book &b) {


cout << [Link] << " " << [Link] << " " <<
[Link] << " " << [Link] << endl;
}
// -----------------------------
// Employee Payroll
// -----------------------------
struct Employee {
string name;
int id;
float basicSalary;
string department;
};

void inputEmployee(Employee &e) {


cout << "Enter name, id, basicSalary, department:
";
cin >> [Link] >> [Link] >> [Link] >>
[Link];
}

void displayEmployee(const Employee &e) {


cout << [Link] << " " << [Link] << " " <<
[Link] << " " << [Link] << endl;
}

void updateSalary(Employee &e, float newSalary) {


[Link] = newSalary;
}
// -----------------------------
// Health Records
// -----------------------------
struct Patient {
string name;
int age;
string disease;
int roomNo;
};

void updateRoom(Patient *p, int newRoom) {


p->roomNo = newRoom;
}

void displayPatient(const Patient &p) {


cout << [Link] << " " << [Link] << " " <<
[Link] << " " << [Link] << endl;
}
// -----------------------------
// Inventory Management
// -----------------------------
struct Product {
string name;
float price;
int quantity;
};

// -----------------------------
// Movie Booking System
// -----------------------------
struct Seat {
int seatNumber;
int row;
bool isBooked;
};

// -----------------------------
// Visitor Temporary Storage
// -----------------------------
struct Visitor {
string name;
string purpose;
string arrivalTime;
};
// -----------------------------
// MAIN FUNCTION – Practice Skeleton
// -----------------------------
int main() {
cout << "\n--- Student Database ---\n";
int nStudents = 2;
Student *students = new Student[nStudents];
for (int i = 0; i < nStudents; i++) inputStudent(students[i]);
for (int i = 0; i < nStudents; i++) displayStudent(students[i]);
delete[] students;

cout << "\n--- Library Book Records (2x2) ---\n";


int shelves = 2, booksPerShelf = 2;
Book **library = new Book*[shelves];
for (int i = 0; i < shelves; i++) library[i] = new Book[booksPerShelf];
// Input and display
for (int i = 0; i < shelves; i++)
for (int j = 0; j < booksPerShelf; j++)
inputBook(library[i][j]);
for (int i = 0; i < shelves; i++)
for (int j = 0; j < booksPerShelf; j++)
displayBook(library[i][j]);
// Free memory
for (int i = 0; i < shelves; i++) delete[] library[i];
delete[] library;
cout << "\n--- Employee Payroll ---\n";
Employee e1;
inputEmployee(e1);
displayEmployee(e1);
updateSalary(e1, [Link] + 500);
cout << "After salary update:\n";
displayEmployee(e1);

cout << "\n--- Inventory Management ---\n";


int nProducts = 2;
Product *products = new Product[nProducts];
for (int i = 0; i < nProducts; i++) {
cout << "Enter name, price, quantity: ";
cin >> products[i].name >> products[i].price >> products[i].quantity;
}
// Display products
for (int i = 0; i < nProducts; i++)
cout << products[i].name << " " << products[i].price << " " << products[i].quantity <<
endl;
delete[] products;
cout << "\n--- Movie Booking System (2x3) ---\n";
int rows = 2, cols = 3;
Seat **seats = new Seat*[rows];
for (int i = 0; i < rows; i++) seats[i] = new Seat[cols];
// Assign seat numbers
int seatNo = 1;
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++) {
seats[i][j].seatNumber = seatNo++;
seats[i][j].row = i + 1;
seats[i][j].isBooked = false; // initially all free
}
seats[0][1].isBooked = true; // booking example
// Display seats
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++)
cout << seats[i][j].seatNumber << (seats[i][j].isBooked ? "(X) " : "(O) ");
cout << endl;
}
for (int i = 0; i < rows; i++) delete[] seats[i];
delete[] seats;
cout << "\n--- Visitor Temporary Storage ---\n";
Visitor *v1 = new Visitor;
cout << "Enter visitor name, purpose, arrivalTime: ";
cin >> v1->name >> v1->purpose >> v1->arrivalTime;
cout << v1->name << " " << v1->purpose << " " << v1->arrivalTime << endl;
delete v1;

cout << "\n--- Health Records ---\n";


int nPatients = 2;
Patient *patients = new Patient[nPatients];
for (int i = 0; i < nPatients; i++) {
cout << "Enter name, age, disease, roomNo: ";
cin >> patients[i].name >> patients[i].age >> patients[i].disease >> patients[i].roomNo;
}
// Update room of first patient
updateRoom(&patients[0], 101);
for (int i = 0; i < nPatients; i++) displayPatient(patients[i]);
delete[] patients;

return 0;
}
10. Conclusion

▪ Structures in C++ are used to group related data


items.

▪ Unlike C, C++ structures can have constructors,


member functions, and access specifiers.

▪ They are useful in organizing complex data.

▪ When more advanced features like data hiding and


inheritance are needed, classes should be used.

You might also like