Chicken Peck Rice: C + + programming 14 learning constructors and destructors

Source: Internet
Author: User

1. I learn the notes of the Chicken Peck Rice course to record the course and progress of learning

2. Constructors

When we declare a variable, if it is initialized, the initialization of the variable is also written to the inner cell when the variable is allocated memory space. Declaring an object has a similar procedure, when the program executes an object declaration statement, it requests a certain amount of memory space from the operating system to hold the object, but can it write the specified initial value when initialized like a generic variable? The object of the class is so complex that it is not easy to achieve this, which requires a constructor to implement.

The function of a constructor is to construct an object with a particular initial value when the object is created, to put the object in an initial state, to be called automatically by the system when the object is created, and we just need to use the default constructor or define the constructor itself, without having to call it.

Constructors are also member functions of a class, in addition to all the characteristics of a member function, there are some differences: the function name of the constructor is the same as the class name, and there is no return value . Constructors are generally declared as public functions, unless we do not allow a class to generate objects that are declared as private or protected properties. When the compiler encounters an object declaration statement, it automatically generates a call statement to the constructor, so we often say that the constructor is automatically called by the system when the object is declared.

If you do not define a constructor for a class, the compiler will automatically generate a default form of the constructor, which does nothing, so why build it? Because C + + calls the constructor when the object is built, if you do not define the constructor yourself, even constructors that do nothing are required.

3. Now add your own defined constructors to the clock class:

1 classClock2 {3 Public:4Clock (intNEWH,intNEWM,intNewS);//constructor Function5voidSetTime (intNEWH,intNEWM,intNewS);6voidShowTime ();7Private:8intHour, Minute, Second;9};

4. Implementation of the constructor function

1  Clock::clock (int. intint  NewS)2{3                  hour=  NEWH; 4                  minute=newm; 5                  second=NewS; 6 }

5. Main function call

1 int Main () 2 {3                 Clock C (0,0,0// implicitly calls the constructor and takes the initial value as an argument.  4                c.showtime (); 5                 return 0 ; 6 }

6. Copy Constructors

We can assign the value of one variable to another variable of the same type, so can you copy the contents of one object to another object of the same class? Yes, we can assign the value of the data variable of the first object to another object's data variable, but it would be cumbersome if the number of data variables were large, and we would need a copy constructor.

A copy constructor is a special constructor, because it is also used to construct objects. It has all the attributes of the constructor. the role of a copy constructor is to initialize another object with an already existing object , and the class type of the two objects should be the same. Define copy constructors in the form of:

1 classclass name2        { 3          Public :4Class name (formal parameter);//constructor Function5Class name (class Name & object name);//copy Constructor6            ...7        };8Class Name:: Class (class name & object name)//implementation of copy constructors9        {   Ten function Body One}

7. Examples of copy constructors

1 class Point2 {3         Public:4Point (intxx=0,intyy=0) {x=xx; y=yy;}5Point &p);6                    intGetX () {returnX;}7                    intGetY () {returnY;}8        Private:9                    intX, Y;Ten};

8. Concrete implementation of the constructor function

1  Point::P oint (Point &P)2{3                   x=p.x; 4                   y=p.y; 5                   cout<<" copy constructor is called "<<Endl; 6 }

9. Destructors

All things are born and gone, and the object of the class is the same as the life cycle, and the same will perish. Chicken Peck Rice Tell us a situation: If an object is declared in a function, the declared object is freed when the function returns to the calling function, as described above in the FUN2 function of object A.

What do you have to do when the object is released? What we often encounter is that the constructor dynamically requests some memory units and releases them at the same time as the objects are released. The knowledge of dynamically allocating memory is behind the chicken peck rice will speak.

Destructors and constructors do the opposite, and it does some cleanup before the object is deleted. Destructors are automatically called by the system when an object is to be deleted , the object disappears after it executes, and the allocated memory space is freed.

A destructor is a public function member of a class whose name is formed before the class name with a "~" and cannot have a return value, and it is different from the constructor function that it cannot have any formal parameters. If a destructor system is not defined, a default destructor is automatically generated, and the default destructor does not do any work. Generally, if we want to do something before the object is deleted, we can write it into a destructor.

10. Examples of destructor functions

1 class Point2 {     3         Public:4Point (intXxintyy);5~Point ();6                    //... Other function Prototypes7        Private:8                   intXintY;9                   Char*p;Ten};

11. The concrete realization of the destructor function

Point::P oint (int xx,int  yy) {                      X=xx;                    Y=yy;                 P=newchar[+];     // dynamically allocating char-type memory in constructors }point::~ Point() {                delete []char;      // releasing dynamically allocated memory prior to class destruction }

Chicken Peck Rice: C + + programming 14 learning constructors and destructors

Related Article

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.