C + + constructor explain __ function

Source: Internet
Author: User
Tags shallow copy

The knowledge of C + + constructors has been introduced in various C + + textbooks, however, beginners often do not pay attention to observe and summarize the characteristics and usage of the various constructors, so I summed up the features of C + + in accordance with my own C + + programming experience, and attached examples, hoping to help beginners. The construction function of C + + class is detailed

What does a constructor do?

Class Counter
{

Public
Constructors for class counter
Features: Class masterpieces as function names, no return type
Counter ()
{
m_value = 0;
}

Private

Data members
int m_value;
}


When the class object is created, it compiles the system object to allocate the memory space and automatically calls the constructor-> the constructor completes the member's initialization work

Eg:counter C1;
The compilation system allocates memory space for each data member (M_value) that the object C1, and calls the constructor counter () to automatically initialize the M_value value of the object C1 set to 0

So

constructor function: Initializes the data member of the object.


Ii. types of constructors

Class Complex
{

Private:
Double m_real;
Double M_imag;

Public

Parameterless constructors
If you create a class you do not write any constructors, the default parameterless constructor is automatically generated, the function is empty, nothing is done
As long as you write one of the following constructors, the system will no longer automatically generate such a default constructor, if you want to have such a parameterless constructor, you need to write it yourself
Complex (void)
{
M_real = 0.0;
M_imag = 0.0;
}

Generic constructors (also called overloaded constructors)
General constructors can have various parameter forms, and a class can have more than one general constructor if the number or type of arguments is different (based on the principle of overloaded functions of C + +)
For example: You can also write a Complex (int num) constructor to come out
Call different constructors When you create an object, depending on the parameters passed in
Complex (double real, double imag)
{
M_real = Real;
M_imag = Imag;
}

Copy constructors (also known as copy constructors)
The copy constructor parameter is a reference to the class object itself, used to copy a new object of that class based on an existing object, typically copying the value of the data member of an existing object into a newly created object in a function
If there is no write copy constructor displayed, the system creates a copy constructor by default, but when there is a pointer member in the class, the default creation of the copy constructor by the system is risky, for specific reasons please inquire about "shallow copy", "Deep copy" article discussion
Complex (const Complex & c)
{
Copy the value of the data member in Object C.
M_real = C.m_real;
m_img = c.m_img;
}

A type conversion constructor that creates an object of this class based on an object of the specified type
For example, the following creates a complex object based on a double type object
Complex::complex (Double R)
{
M_real = R;
M_imag = 0.0;
}

equals operator overload
Note that this similar copy constructor copies the value of the object of this class on the right side to the object to the left of the equal sign, which is not part of the constructor, and the object on both sides of the equal sign must already be created
If the Write = operator overload is not displayed, the system also creates a default = operator overload, doing only some basic copy work
Complex & operator= (const Complex &RHS)
{
First detect whether the right side of the equal sign is the object on the left, and if this object itself, return directly
if (this = = &RHS)
{
return * this;
}

Copy the member to the right of the equal sign to the object on the left
This->m_real = Rhs.m_real;
This->m_imag = Rhs.m_imag;

Send the object to the left of the equal sign again
The purpose is to support the EG:A=B=C system first run B=c
Then run a= (B=c's return value, which should be the B-object after copying the C value)
return * this;
}

};

The following class objects defined above are used to illustrate the use of each constructor:

void Main ()
{
Call the parameterless constructor, and the data member initial value is assigned to 0.0
Complex c1,c2;

Call a generic constructor, the data member initial value is assigned to the specified values
Complex C3 (1.0,2.5);
You can also use the following form
Complex C3 = Complex (1.0,2.5);

Assign the value of the C3 data member to C1
Since C1 has been created beforehand, no constructors are called
Only the = number operator overload function is called
C1 = C3;

Calling type conversion constructors
The system first calls the type conversion constructor, creates 5.2 as a temporary object of this class, and then calls the Equals operator overload, assigning the temporary object to the C1
C2 = 5.2;

Call copy constructor (there are two ways to invoke it)
Complex c5 (C2);
Complex C4 = c2; Note and = operator overloading distinguishes, where the object on the left side of the equal sign is not previously created, it is necessary to invoke the copy constructor, the parameter is C2



}

Iii. Thinking and testing

1. Carefully observe the copy constructor

Complex (const Complex & c)
{
Copy the value of the data member in Object C.
M_real = C.m_real;
m_img = c.m_img;
}

Why you can access private members of object C directly in a function.

2. Challenge questions to understand the difference between reference and value transfer

Complex test1 (const complex& c)
{
return C;
}

Complex test2 (const Complex c)
{
return C;
}

Complex Test3 ()
{
Static Complex C (1.0,5.0);
return C;
}

complex& test4 ()
{
Static Complex C (1.0,5.0);
return C;
}

void Main ()
{
Complex a,b;

The following functions are called several times during the execution of the function, and what constructor is invoked.

Test1 (a);
Test2 (a);

b = test3 ();
b = test4 ();

Test2 (1.2);
Does the following statement make an error?
Test1 (1.2); Test1 (Complex (1.2)).
}

Iv. Appendix (Light Copy and deep copy)

As mentioned above, if you do not have a custom copy constructor, the system creates a default copy constructor, but the default copy constructor created by the system only performs a "shallow copy", and the value one by one of the data member of the copied object is assigned to the newly created object, if the data member of the class has a pointer member, Causes the new object's pointer to have the same address as the pointer to the copied object, and an error occurs when the pointer is removed to repeat the delete two times. Here is an example:

"Shallow copy and deep copy"

#include <iostream.h>
#include < string.h>
Class Person
{
Public:

Constructors
Person (char * pN)
{
cout << "General constructors are called!\n";
M_pname = new Char[strlen (PN) + 1];
Open a memory block in the heap to store the string that the PN refers to
if (m_pname!= NULL)
{
If M_pname is not a null pointer, copy the string referred to by the parameter pointer pn to it
strcpy (M_pname, PN);
}
}

System-created default copy constructor, only bit-mode copy
Person (person & P)
{
To point two string pointers to the same address location
M_pname = P.m_pname;
}

~person ()
{
Delete M_pname;
}

Private:

char * M_PNAME;
};

void Main ()
{
Person Mans ("Lujun");
Person Woman (Mans);

As a result, both the man and woman's pointers point to the same address.

When the function ends the destructor
The same address was delete two times
}


You design the copy constructor below to implement a "deep copy", that is, not to point the pointer at the same address, but to reapply the pointer data member of a piece of memory to the new object
Person (person & CHS);
{
Assigning space to a pointer data member for a new object with operator new
M_pname= new Char[strlen (P.m_pname) + 1];

if (m_pname)
{
Copy content
strcpy (M_pname, chs.m_pname);
}

The m_pname of the newly created object is no longer pointing to the same address as the m_pname of the original object CHS
This article is derived from the

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.