In: Computer Science
We had plenty of new concepts to study for this week. List one concept and describe it to the class. Do not duplicate concepts described by other students. I will start:
We learned about the Copy Constructor. The C++ supplies each class with a default copy constructor. This function is invoked when a new object is created and initialized or when an object is passed as a value parameter to a function. The default copy constructor performs a shallow copy, the values of the data fields in the exiting object is copied over to the newly created object. The default constructor is enough and works fine if the class has no pointer data field. A class that has a pointer data member that points to allocated memory will need a customized copy constructor (a deep copy) since the default constructor only copies the address the pointer is holding and not the allocated memory. The Course class with the student data member is a good example.
Code
#include<iostream>
#include<cstring>
using namespace std;
class DeepCopyExample
{
char *s_copy;
public:
DeepCopyExample (const char *str)
{
s_copy = new char[16]; //Dynamic memory alocation
strcpy(s_copy, str);
}
DeepCopyExample (const DeepCopyExample &str)
{
s_copy = new char[16]; //Dynamic memory alocation
strcpy(s_copy, str.s_copy);
}
~DeepCopyExample()
{
delete [] s_copy;
}
void display()
{
cout<<s_copy<<endl;
}
};
/* main function */
int main()
{
DeepCopyExample c1("JayJoshi");
//object created using the deep copy
DeepCopyExample c2 = c1; //copy constructor
c1.display();
cout<<"\nC2 object that is created using deep
copy."<<endl;
c2.display();
return 0;
}
output
If you have any query regarding the code please ask me in the
comment i am here for help you. Please do not direct thumbs down
just ask if you have any query. And if you like my work then please
appreciates with up vote. Thank You.