0% found this document useful (0 votes)
6 views13 pages

Week 9

The document provides an overview of structures, pointers, and copy constructors in C++. It explains how structures group different variable types, how pointers store memory addresses, and the significance of copy constructors for creating object copies. Additionally, it includes examples and lab tasks related to these concepts, such as defining a book structure, manipulating temperature with pointers, and implementing classes for matrices and vehicles.

Uploaded by

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

Week 9

The document provides an overview of structures, pointers, and copy constructors in C++. It explains how structures group different variable types, how pointers store memory addresses, and the significance of copy constructors for creating object copies. Additionally, it includes examples and lab tasks related to these concepts, such as defining a book structure, manipulating temperature with pointers, and implementing classes for matrices and vehicles.

Uploaded by

usmanqasim845
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

What is a structure?

 A structure (struct) is a user-defined data type in C++.


 It groups different variables (even of different types) into a single unit.
 You can think of it like a lightweight class (in fact, in C++, structs and classes are very
similar — the only difference is that structs have public members by default).

#include <iostream>
using namespace std;

// Define a structure
struct Student {
string name;
int rollNumber;
float marks;
};

int main() {
// Create a structure variable
Student s1;

// Assign values
s1.name = "John Doe";
s1.rollNumber = 101;
s1.marks = 89.5;

// Display values
cout << "Name: " << s1.name << endl;
cout << "Roll Number: " << s1.rollNumber << endl;
cout << "Marks: " << s1.marks << endl;

return 0;
}

Output:

Name: John Doe


Roll Number: 101
Marks: 89.5
Key Points:

 You can have multiple instances (objects) of a struct.


 Members of a struct can be of different data types.
 Structs can even have functions inside (like classes).

Structure with Functions (C++ Style)

#include <iostream>
using namespace std;

struct Rectangle {
int length;
int breadth;

// Function inside structure


int area() {
return length * breadth;
}
};

int main() {
Rectangle r1 = {10, 5};

cout << "Area of Rectangle: " << r1.area() << endl;

return 0;
}

What is a Pointer?

 A pointer is a variable that stores the address of another variable.


 Instead of holding a direct value (like int x = 5), a pointer holds the memory location.

Basic Pointer Syntax:

type *pointerName;
Example:

int *p;

Here, p is a pointer to an integer.

Example 1: Simple Pointer

#include <iostream>
using namespace std;

int main() {
int x = 10;
int *p; // Pointer to int

p = &x; // Store address of x in p

cout << "Value of x: " << x << endl;


cout << "Address of x: " << &x << endl;
cout << "Pointer p holds: " << p << endl;
cout << "Value at address stored in p (*p): " << *p << endl;

return 0;
}

Output:

Value of x: 10
Address of x: 0x61ff08 (example address)
Pointer p holds: 0x61ff08
Value at address stored in p (*p): 10

Example 2: Changing Value Using Pointer

#include <iostream>
using namespace std;

int main() {
int a = 5;
int *ptr = &a;

cout << "Before: " << a << endl;


*ptr = 20; // Change value of 'a' using pointer

cout << "After: " << a << endl;

return 0;
}

Output:

Before: 5
After: 20

Imagine:
a = 10
Address of a: 0x1234

p = &a
p holds: 0x1234

*p means value at address p, which is 10

Copy Constructor

A copy constructor is a special type of constructor in object-oriented programming (like in C+


+) that creates a new object by copying an existing object. It makes an exact copy of another
object.

ClassName (const ClassName &oldObject);

 It takes a reference to an object of the same class.


 It usually copies all the data members from the old object to the new one.
Example 1: Basic Copy Constructor
#include <iostream>
using namespace std;

class Person {
string name;
int age;

public:
// Constructor
Person(string n, int a) {
name = n;
age = a;
}

// Copy Constructor
Person(const Person &p) {
name = p.name;
age = p.age;
}

void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};

int main() {
Person person1("Alice", 25);
Person person2 (person1); // Copy constructor is called here

cout << "Person 1: ";


person1.display();

cout << "Person 2: ";


person2.display();

return 0;
}

Output:

Person 1: Name: Alice, Age: 25


Person 2: Name: Alice, Age: 25
Quick explanation:

 Person(const Person &p) is the copy constructor.


 It creates a new object (person2) by copying values from an existing object (person1).

We pass by const reference (const Person &p) to avoid unnecessary copying and to
protect the source object.

Example:2
#include <iostream>
using namespace std;

class Student {
public:
int age;

// Constructor
Student(int a) {
age = a;
}

// Copy Constructor
Student(const Student &s) {
age = s.age;
}

void display() {
cout << "Age: " << age << endl;
}
};

int main() {
Student s1(20); // normal constructor
Student s2 = s1; // copy constructor

s1.display(); // Age: 20
s2.display(); // Age: 20

return 0;
}

Here, s2 is created by copying s1.


Why do we need a copy constructor?

 To copy objects properly (especially if the object has pointers or dynamic memory).
 To pass objects by value to functions.
 To return objects from functions.

Shallow Copy Constructor

A shallow copy constructor in C++ is when you copy all the fields of an object exactly as they
are, including pointers — just copying their addresses, not the actual data they point to.

Shallow Copy = "Just copy the surface"

If an object has a pointer inside, both the original and the copied object will point to the same
memory.

Example

#include <iostream>
using namespace std;

class Example {
public:
int *ptr;

// Constructor
Example(int val) {
ptr = new int(val);
}

// Shallow Copy Constructor


Example(const Example &obj) {
ptr = obj.ptr; // just copying the pointer address
}

void display() {
cout << "Value: " << *ptr << endl;
}
};

int main() {
Example e1(10);
Example e2 = e1; // shallow copy
e1.display(); // Value: 10
e2.display(); // Value: 10

*(e1.ptr) = 20; // change e1's value

e1.display(); // Value: 20
e2.display(); // Value: 20 (e2 also changed!)

return 0;
}

Note:

 Changing e1 also changed e2!


 Because they share the same memory.

Problems with Shallow Copy:

 If you delete one object, the pointer becomes invalid for the other object.
 It can cause program crashes.

Related: Deep Copy

 Deep copy creates a new memory and copies the actual data — so both objects are
fully independent.
 Deep copy avoids the problems shallow copy causes.

#include <iostream>

using namespace std;


class student{
private:
int id;
string name;
int* x;
public:
student()
{

}
student(int id,string name,int temp)
{
this->id=id;
this->name=name;
this->x=new int;
*(this->x)=temp;

}
student(student &object)
{
this->id=object.id;
this->name=object.name;
this->x=new int;
*(this->x)=*(object.x);

void display()
{
cout<<" name"<<name<<endl;
cout<<" id"<<id<<endl;
cout<<" ptr "<<x<<endl;
}
~student()
{
cout<<" destructor is called"<<endl;
}

};
int main()
{
cout << "Hello world!" << endl;
student ob1(123,"abc",678);
student ob2(ob1);
cout<<" display for obj1 "<<endl;
ob1.display();
cout<<" display obj2 "<<endl;
ob2.display();

return 0;
}

Output:
Hello world!
display for obj1
nameabc
id123
ptr 0x2d8c6c0
display obj2
nameabc
id123
ptr 0x2d8c6e0
destructor is called
destructor is called

Array as data member in class using construct:


#include <iostream>
using namespace std;
class MyClass {
private:
int myArray[5]; // Array as data member
public:
MyClass() {
for (int i = 0; i < 5; ++i) {
myArray[i] = i * 10;
}
}
// Member function to display array elements
void displayArray() {
cout << "Array elements:";
for (int i = 0; i < 5; ++i) {
cout << " " << myArray[i];
}
cout << endl;
}
// Setter function to modify array elements
void setArrayElement(int index, int value) {
if (index >= 0 && index < 5) {
myArray[index] = value;
} else {
cout << "Invalid index!" << endl;
}
}
};
int main() {
MyClass obj;
// Display the initial array elements
obj.displayArray();
// Modify an array element using the setter function
obj.setArrayElement(2, 100);

// Display the modified array elements


obj.displayArray();
return 0;
}

LAB TASKS
Lab Task 01:

You are designing a simple library management system.


In a library, each book has the following information:

 Title (string)
 Author (string)
 ISBN number (integer)
 Price (float)

Scenario:
The library wants a basic system where the librarian can enter details of a book and then view
them.

Your task:

1. Define a struct named Book with the given details.


2. Create a variable of the Book structure.
3. Assign values to the book’s properties manually (you can choose any values).
4. Display the details of the book using cout.

Example Output:
Book Title: The Great Gatsby
Author: F. Scott Fitzgerald
ISBN: 123456789
Price: 299.99
LAB Task 02:

You are working as a developer for a temperature monitoring system. The system measures the
current temperature in a machine. Sometimes, based on conditions (like cooling or heating),
the temperature needs to be modified indirectly using pointers. You are asked to:

1. Create an integer variable called temperature and assign it an initial value (e.g., 75).
2. Create a pointer that stores the address of temperature.
3. Display the current temperature using the pointer.
4. Simulate a cooling system by decreasing the temperature by 10 using the pointer.
5. Display the updated temperature.

Example Output:

Current Temperature: 75
Temperature via Pointer: 75
Temperature after Cooling: 65

Lab Task 03:


Create a class called Matrix to represent a 2x2 matrix. Include the following:
 Private data members for the elements of the matrix (integers).
 A default constructor that initializes the matrix to zeros.
 A parameterized constructor that takes four integers to initialize the matrix elements.
 A copy constructor that creates a deep copy of another Matrix object.
 A member function display() to display the elements of the matrix.
Your task is to demonstrate the use of the copy constructor by creating two Matrix objects and
copying one into another, ensuring that changes in one object do not affect the other.

LAB Task 04:


Create a class Vehicle representing a vehicle with attributes like brand (string), year (integer),
and price (float). Implement the following constructors:
 Default constructor that initializes the brand to "Unknown", year to the current year, and
price to 0.0.
 Parameterized constructor that takes the brand and year as arguments and sets the price to
a default value of 10000.0.
 Overloaded constructor that takes all three attributes as arguments.
Now, create several Vehicle objects using different constructors and display their details to
ensure the constructors with default arguments work correctly.

LAB Task 05:


Create a class Image to represent an image file. The Image class should have the following
attributes:
 Image name (string)
 Image size (integer)
 Image data (pointer to image data)
 Implement the following functionalities:
 A default constructor that initializes the image with default values.
 A parameterized constructor that takes the image name, size, and image data as
arguments.
 A copy constructor that performs a deep copy of another Image object.
Create two Image objects using the default constructor and the parameterized constructor.
Modify the image data in one object and display the image details of both objects to demonstrate
deep copy and resource management.

You might also like