Class-generated member functions by default

Source: Internet
Author: User

six member functions generated by default for a class

first, the constructor functionwe know that the data members of a class cannot be initialized at the time the class is declared, because the class is not an entity, but an abstract data type and does not occupy storage space. To solve this problem, C + + provides constructors to handle initialization of objects.
1. Function of the constructorA constructor is a special member function that, unlike other member functions, is called automatically when an object is instantiated and is executed only once, and it cannot be called by the user. The constructor does not have this pointer. The constructor's name is fixed, is the same as the class name, cannot be arbitrarily named by the user, it has no type, and no return value . The function of the constructor is defined by the user, and the user designs the function body and function parameters according to the requirements of the initialization. If the user does not define the constructor themselves, the C + + system automatically generates a constructor called the default constructor or the default constructor. Just this constructor is empty, nothing is done, but it is still called.
Example: Designing a Date class and defining constructors
Classdate{public:                date ()             //constructor                {                                _year = 0;     Initialized to 0                                _month = 0;                                _day = 0;                } Private:                int _year;          General data members begin with _ or begin with m_                int _month;                int _day;};



2. Constructor with parameterssometimes users want to assign different initial values to different objects, then they must use the constructor with parameters to implement different initializations. The corresponding argument is given when the object is defined. the general form of the first part of a construction function:constructor Name (type 1 parameter 1, type 2 parameter 2, ...)because the user cannot call the constructor, the arguments are given when the object is defined: Class Name Object name (argument 1, Argument 2, ... ) );Example:
Classdate{public:                Date (int year, intmonth,intday)             //constructor                {                                _year =year;                                _month =month;                                _day =day;                } Private:                int _year;          General data members begin with _ or begin with m_                int _month;                int _day;}; Intmain () {                date D1 (7, +);   Defines an object that has an initial value of                system ("pause");                return 0;}



3. Initialization of data members with parameter listC + + also provides a way to initialize data members-the parameter initialization table. This method does not initialize the data members in the function body, but is implemented at the first part of the functor. Example:
Classdate{public:                date (int, int month,int day): _year (year)                                , _month (month)                                , _day (day)                {                } Private:                int _year;          General data members begin with _ or begin with m_                int _month;                int _day;};


that is, add a colon at the end of the first letter number, and then list the initialization table for the parameter, separated by commas.
Why do you have this method??? This is because some data members such as references, const-modified variables must be initialized at the time of creation, so they can only be initialized by initializing the list. And this method is more efficient.
4. Constructors can be overloadedAlthough constructors can have multiple, for each object, only one of the constructors is executed when an object is created. It is also important to emphasize that if you declare an object that is not a parameter, you should writedate D1;and should not be writtendate D1 (); This is a function declaration, the type is date, the function name is D1, the argument is empty
5. Constructors that use default parametersthe values of the parameters in the constructor can be passed either through an argument or as some default value, and if the user does not specify an argument value, the compilation system makes the formal parameter the default value. It is a good idea to specify a default value when declaring a constructor, rather than specifying a default value only when the constructor is defined. After you define a constructor that is all default parameters in a class, you cannot define an overloaded constructor.
Second, copy the constructor function1, copy constructor is to use an existing object to replicate a number of identical objects. Example: Date D2 (D1), whose function is to create a new object D2 with the existing object D1, and D1 is exactly the same as D2. The copy constructor is also a constructor, but he has only one parameter (this argument can only be an object of this class), and it takes the object's usual reference form. The role of a copy constructor is to assign the member value one by one of the argument object to the corresponding member in the new object. Example:
Classdate{public:                Date (int year, Int. Month,int Day): _year (year)                                , _month (month)                                , _day (day)                {                }< C9/>date (const date &D)         //copy constructor                {                                _year =d._year;                                _month =d._month;                                _day =d._day;                } Private:                int _year;          General data members begin with _ or begin with m_                int _month;                int _day;};



Note: The copy constructor creates a new object from scratch. The parameter of a copy constructor can only be a reference to the object of this class, and an infinite recursion is thrown if it is not a reference. The copy constructor is generated by the class by default, but when it comes to dynamic memory, the default generated copy constructor does not meet our requirements, and we need to define a copy constructor ourselves as needed.
2. When do I call the copy constructor? you need to create a new object in the program and initialize it with another object of the same kind. when the parameters of a function are objects of the class. When calling a function, the argument object needs to be fully passed to the parameter, that is, a copy of the argument needs to be established. The return value of the function is the object of the class. When the function call is complete and the return value is brought back to the function call, the object in the function needs to be copied to a temporary object to return
third, the destructor functionA destructor is also a special member function, which acts in contrast to a constructor, whose name is preceded by a "~" symbol in front of the class name. It is automatically called by the system before the object is released.
1. The function of destructors is not to delete objects, but to do some cleanup work when undoing objects. such as closing open files, freeing up dynamic memory and other work. 2. Destructors do not return any values, no function types, no parameters, and therefore cannot be overloaded. 3. Order of calling constructors and destructorsbecause of the relationship of the function pressure stack, the first structure of the post-destructor, after the construction of the first destruction. If there are global objects or static local objects, they are 2 destroyed when the main function ends or when the Exit function is called.
iv. assignment operator overloading1, if two or more objects have been defined, then the same objects can be assigned to each other, that is, the value of one object can be assigned to another homogeneous object. The value of the object referred to here is the value of all data members in the object. the assignment between objects is implemented by the assignment operator ' = ' overload, which copies the value one by one of an object to the corresponding member of another object. such as:
Classdate{public:                Date (int year, Int. Month,int Day): _year (year)                                , _month (month)                                , _day (day)                {                }< C5/>date operator= (date&d)               //copy operator overload                {                                _year =d._year;                                _month =d._month;                                _day =d._day;                } Private:                int _year;          General data members begin with _ or begin with m_                int _month;                int _day;};



the general form of an object assignment:Object Name 1 = object Name 2;
2, assignment operator assignment, the data members of the class can not include the dynamic allocation of data, otherwise at the time of the destruction of the same piece of memory will be released multiple times, resulting in an error. 3, to distinguish between assignment operator overloading and copy constructor functions. An assignment operator is a value that is assigned to an object that has already been created.
take address operator overloading and const-decorated fetch-address operator overloading these two default member functions are generally not redefined.Example:
Classdate{public:                Const date * operator& () const                {                                return this;                } Private:                int _year;                int _month;}


          

Class-generated member functions by default

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.