C ++ Constructor

Source: Internet
Author: User

The knowledge of c ++ constructor has been introduced in a variety of c ++ textbooks. However, beginners often do not pay much attention to the characteristics and usage of the constructor, therefore, based on my own c ++ programming experience, I have summarized the features of various constructor functions in c ++ and attached examples to help beginners.

C ++ class Constructor

I. What are Constructors?

Class Counter
{

Public:
// Constructor of the Counter class
// Feature: the class name is used as the function name and no return type is returned.
Counter ()
{
M_value = 0;
}

Private:

// Data member
Int m_value;
}


When this class of object is created, the Compilation System Object allocates memory space and automatically calls this constructor-> the constructor completes member initialization.

Eg: Counter c1;
The compilation system allocates memory space for each data member (m_value) of the object c1, and calls the constructor Counter () to automatically initialize the m_value of the object c1 and set it to 0.

Therefore:

The role of the constructor is to initialize the data members of an object.


Ii. Types of Constructor

Class Complex
{

Private:
Double m_real;
Double m_imag;

Public:

// No parameter Constructor
// If you do not write any constructor to create a class, the system automatically generates the default non-argument constructor. The function is empty and does nothing.
// As long as you write a constructor below, the system will not automatically generate such a default constructor. If you want such a constructor, you need to write it out on your own.
Complex (void)
{
M_real = 0.0;
M_imag = 0.0;
}

// General constructor (also weigh the loaded constructor)
// A General constructor can have various parameter forms. A class can have multiple General constructor, provided that the number or type of parameters are different (based on the principle of c ++ overload function)
// For example, you can also write a Complex (int num) constructor.
// Call different constructors based on different input parameters when creating an object
Complex (double real, double imag)
{
M_real = real;
M_imag = imag;
}

// Copy constructor (also called copy constructor)
// The copy constructor parameter is a reference of the class object. It is used to copy a new class object based on an existing object, in a function, the data member values of an existing object are copied to the newly created object.
// If no displayed write-copy constructor is displayed, the system creates a copy constructor by default, by default, this copy constructor is created by the system. For details about the causes, refer to the articles on "shortest copy" and "Deep copy ".
Complex (const Complex & c)
{
// Copy the data member value in Object c
M_real = c. m_real;
M_img = c. m_img;
}

// Type conversion constructor, which creates an object of this Class Based on a specified type object
// For example, a Complex object is created based on a double object.
Complex: Complex (double r)
{
M_real = r;
M_imag = 0.0;
}

// The equal sign operator is overloaded.
// Note: this is similar to the copy constructor. Copy the value of the = object on the right to the object on the left of the equal sign. It does not belong to the constructor, objects on both sides of the equal sign must have been created
// If no explicit write = Operator overload is displayed, the system will also create a default = Operator overload to only perform some basic copy operations.
Complex & operator = (const Complex & rhs)
{
// First, check whether the object on the right of the equal sign is the object on the left. If the object is itself, the system returns
If (this = & rhs)
{
Return * this;
}

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

// Output the object on the left of the equal sign again
// The purpose is to support the interconnection of eg: a = B = c system first run B = c
// Then run a = (B = c's return value. Here it should be the B object after copying the c value)
Return * this;
}

};

The class objects defined above are used to describe the usage of each constructor:

Void main ()
{
// Call the no-argument constructor. The initial value of the data member is assigned as 0.0.
Complex c1, c2;

// Call a common constructor. The initial value of the data member is assigned a specified value.
Complex c3 (1.0, 2.5 );
// You can also use the following format
Complex c3 = Complex (1.0, 2.5 );

// Assign the value of the c3 data member to c1
// Since c1 has been created in advance, no constructor will be called.
// Only the = Operator is called to reload the Function
C1 = c3;

// Call the type conversion Constructor
// The system first calls the type conversion constructor, creates 5.2 as a temporary object of this class, then calls the equal sign operator to overload it, and assigns the temporary object to c1
C2 = 5.2;

// Call the copy constructor (the following two call methods are available)
Complex c5 (c2 );
Complex c4 = c2; // note that the object on the left of the equal sign is not created beforehand. Therefore, you need to call the copy constructor. The parameter is c2.



}

Iii. Thinking and Testing

1. Carefully observe the replication Constructor

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

Why can a function directly access the private member of Object c?

2. Challenge question, understanding 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 number of constructor calls during the following function execution. What constructor is called?

Test1 ();
Test2 ();

B = test3 ();
B = test4 ();

Test2 (1.2 );
// Will the following statement fail?
Test1 (1.2); // What about test1 (Complex (1.2?
}
 
Iv. Appendix (shallow copy and deep copy)
 
As mentioned above, if there is no custom replication constructor, the system will create the default replication constructor, but the default replication constructor created by the system will only execute "shortest copy ", values of the Data members of the Copied object are assigned to the newly created object. If the data member of this class has pointer members, the pointer of the new object is directed to the same address as the pointer of the Copied object. When you delete the pointer, duplicate delete operations may occur. The following is an example:
 
[Shallow copy and deep copy]
 
# Include <iostream. h>
# Include <string. h>
Class Person
{
Public:

// Constructor
Person (char * pN)
{
Cout <"the constructor is called! \ N ";
M_pName = new char [strlen (pN) + 1];
// Open a memory block in the heap to store the string indicated by pN
If (m_pName! = NULL)
{
// If m_pName is not a null pointer, copy the string referred to by the parameter pN to it.
Strcpy (m_pName, pN );
}
}

// The default copy constructor created by the system. Only the bitwise copy function is used.
Person (Person & p)
{
// Point the two string pointers to the same address location
M_pName = p. m_pName;
}

~ Person ()
{
Delete m_pName;
}

Private:

Char * m_pName;
};

Void main ()
{
Person man ("lujun ");
Person woman (man );

// As a result, the pointers of man and woman point to the same address.

// Function end destructor
// Delete the same address twice
}


// The copy constructor is designed below to implement "Deep copy", that is, the pointer is not directed to the same address, but a memory is re-applied to the pointer data members of the new object.
Person (Person & chs );
{
// Use the new operator to allocate space for the pointer data members of the new object.
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 and the m_pName of the original object chs no longer point to the same address

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.