Deep copy and shallow copy constructors for C + + class objects

Source: Internet
Author: User
Tags constructor shallow copy

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 ();
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.