OOP ASSIGNMENT
By: Muhammad Ibrahim Kamal (BCS02163040)
3rd Semester, Section “C”.
Task 1:
Task 2:
Task 3:
Difference B/W Deep and Shallow Copy
A shallow copy of an object, copies the values of all
the data members into another abject of same
class. When members are dynamically allocated, the
built-in copy constructor and operator= are not
going to be enough. In case of a class having
dynamically allocated members like below abc class.
class abc
{
public:
class(const char*str);
~class();
private:
char* stored;
};
We have to provide three things for class abc.
1. Write a proper copy constructor.
2. Overload the assignment operator.
3. Write a destructor that frees the memory.
When we provide above three things to avoid
memory leaks or undefined behavior, this operation
is called deep copy.
Shallow Copy Example with Issue
#include <string.h>
using namespace std;
class MyName
{
public:
MyName (const char *str);
~MyName ();
private:
char *emp_name;
};
MyName::MyName (const char *str)
{
emp_name = new char[strlen (str) + 1];
strcpy (emp_name, str);
}
MyName::~MyName ()
{
delete[]emp_name;
}
int main ()
{
MyName name ("wikistack");
MyName name1 = name; // initialie name1 from name object
return 0;
}
Here we will have issue after running the above code. Because we have not
Provide copy constructor and overloaded assignment operator in class MyName.
Deep Copy Example without Issue
#include<iostream>
#include<string.h>
using namespace std;
class MyName
{
public:
MyName (const char *str);
~MyName ();
MyName (const MyName & another);
void operator = (const MyName & another);
private:
char *emp_name;
};
MyName::MyName (const char *str)
{
emp_name = new char[strlen (str) + 1];
strcpy (emp_name, str);
}
MyName::~MyName ()
{
delete[]emp_name;
}
MyName::MyName (const MyName & another)
{
emp_name = new char[strlen (another.emp_name) + 1];
strcpy (emp_name, another.emp_name);
}
void
MyName::operator = (const MyName & another)
{
char *temp = new char[strlen (another.emp_name) + 1];
strcpy (temp, another.emp_name);
delete[]emp_name;
emp_name = temp;
}
int main ()
{
MyName name ("wikistack");
MyName name1 = name;
return 0;
}
Here we will have no issue after running the above code.
__________________________
__________________________
__________________________
_______________________