π One-stop destination for all your technical interview Preparation π
This pointer can be used to,
Example:
class mobile
{
string model;
int year_of_manufacture;
public:
void set_details(string model, int year_of_manufacture)
{
this->model = model;
this->year_of_manufacture = year_of_manufacture;
}
void print()
{
cout << this->model << endl;
cout << this->year_of_manufacture << endl;
}
};
int main()
{
mobile redmi;
redmi.set_details("Note 7 Pro", 2019);
redmi.print();
}
// Output:
// Note 7 Pro
// 2019
A shallow copy can be made by simply copying the reference.
class students()
{
int age;
char* names; // names is a pointer to a char array
public:
students(int age, char* names)
{
this->age = age;
// shallow copy
this->names = names;
// here we are putting the same array.
// we are just copying the reference
}
};
To perform Deep copy, we need to** explicitly define the copy constructor** and assign dynamic memory as well if required. Also, it is necessary to allocate memory to the other constructorsβ variables dynamically.
class student()
{
int age;
char* names;
public:
student(int age, char* names)
{
this->age = age; // deep copy
this->names = new char[strlen(names) + 1];
strcopy(this->names, names);
// Created new array and copied data
}
};