We've learned about the constructors and destructors of classes before we learn this chapter, and for ordinary types of objects, replication between them is simple, for example:
int a = 10;
int b =a;
The objects of the class that you define are also objects, and no one can prevent us from replicating in the following ways, such as:
#include <iostream>
using namespace Std;
Class Test
{
Public
Test (int temp)
{
P1=temp;
}
Protected
int p1;
};
void Main ()
{
Test A (99);
Test B=a;
}
Common objects and class objects are the same objects, there are similarities and differences between the characteristics of the class object, and the objects are not the same, and when the same method of copying occurs on different objects, then the operation of the system is not the same, in the case of class objects, The same type of class object is the copy constructor to complete the entire replication process, in the above code, we do not see the copy constructor, also completes the replication work, this is why? Because when a class does not have a custom copy constructor, the system automatically provides a default copy constructor to complete the replication work.
So, to illustrate the situation, in general terms (take the code above for example), let's define a copy constructor like the default copy constructor of the system and see how it works inside!
The code is as follows:
#include <iostream>
using namespace Std;
Class Test
{
Public
Test (int temp)
{
P1=temp;
}
Test (test &c_t)//This is the custom copy constructor
{
cout<< "Enter copy constructor" <<endl;
p1=c_t.p1;//This sentence if removed can not complete the copy work, this sentence copy process core statement
}
Public
int p1;
};
void Main ()
{
Test A (99);
Test B=a;
cout<<b.p1;
Cin.get ();
}