Objective C ++ clause 5: Understand the default functions written and called by C ++.

Source: Internet
Author: User

Compile to declare a default constructor, a copy constructor, a copy assignment operator, and an destructor for an empty class. All these are public and inline:

Class empty {};

It is like writing code like this:

Class empty {

Empty (){...}

Empty (const empty & RHs ){...}

~ Empty (){...}

Empty & operator = (const empty & RHs ){...}

};

Only when these functions are needed will they be created by the compiler.

The default constructor and destructor mainly call the constructor and destructor of base classes and non-static member variables. The Destructor generated by the compiler is non-virtual, unless the base class of the class itself declares a virtual destructor (the virtual attribute comes from the base class ). The copy constructor uses the member variables of the Copied object as the initial values to construct its own member variables. For the built-in type, it copies each bits for initialization. The execution of the copy assignment operator is basically the same as that of the copy structure.

Class nameobject {
Public:
Nameobject (STD: string & name, const Int & value );
PRIVATE:
STD: string & namevalue;
Const int objectvalue;
};

Inline void test05 ()
{
STD: String newdog ("Persephone ");
STD: String oledog ("Satch ");
Nameobject P (newdog, 2 );
Nameobject S (oledog, 36 );

// P = s; // error c2582: 'nameobject': 'operator = 'function is unavailable
}

C ++ does not allow reference to point to different objects, and cannot change the const object. Therefore, the copy assignment operator generated by the compiler is powerless. If you want to assign values, you can only define the copy assignment operator by yourself.

If base classes declares the copy assignment operator as private, the compiler rejects generating a copy assignment operator for Its Derived classes.

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.