C + + Member objects and enclosing classes

Source: Internet
Author: User

Member object: the member variable of one class is an object of another class
The class that contains the member object is called the enclosing class (enclosing)
The following code:

classCtyre {Private:    intradius; intwidth; Public: Ctyre (intRintW): Radius (r), Width (w) {}//Init list}; classcengine {};classCcar {//Automotive class, closed classPrivate:    intPrice ;    Ctyre Tyre; Cengine engine; Public: Ccar (intPintTrinttw);}; Ccar::ccar (intPintTrinttw):p rice (p), Tyre (tr, TW) {}intMain () {Ccar car (20000, -,225); return 0;}

If the Ccar class does not define a constructor, then Ccar car; A compilation error will occur
The compiler doesn't know how to initialize Car.tyre
Car.engine initialization is not a problem, use the default constructor

How to initialize a statement, "Member objects in an object", that generates an enclosing class object

When defining a constructor for an enclosing class, add an initialization list:
Class Name:: constructor (Parameter table): member variable 1 (parameter table), member variable 2 (parameter table), ...
{
...
}

Call Order
When the enclosing class object is generated, the
First step: Execute constructors for all member objects
Step Two: Execute the constructor of the enclosing class

constructor invocation order for member objects
1. Consistent with the order in which member objects are described in the class
2. Regardless of the order in which they appear in the member initialization list

When the object of the enclosing class dies,
First step: Execute the destructor of the enclosing class first
Step two: Perform the destructor for the member object

C + + Member objects and enclosing 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.