C ++ Session 5: Member objects and Enclosing class)

Source: Internet
Author: User

C ++ Session 5: Member objects and Enclosing class)
Member object: The member variable of a class is the object of another class.
Closed class: class containing Member objects


Example:

class Tyre { private:int radius; int width; public:Tyre(int r, int w):radius(r), width(w) { }};class Engine { };



Class Car {// This class is a so-called closed class // including the member object Engine and Tyreprivate: int price; Tyre tyre; Engine engine Engine; public: Car (int p, int tr, int tw) ;}; Car: Car (int p, int tr, int w): price (p), tyre (tr, w ){}; int main () {Car car (20000,17, 225); return 0 ;}


Specifications:
1. When a member object appears, the constructor of this class should contain the initialization of the member. If the member initialization list of the constructor does not initialize the member object, the default constructor of the member object is used.
2. When creating a class object, call its constructor first. However, if this class has a member object, you must first execute the constructor of the class to which the member object belongs. After all member objects execute their own class constructor, then execute the constructor of the current class.


For example:
class Tyre {public:Tyre() { cout << "Tyre contructor" << endl; }~Tyre() { cout << "Tyre destructor" << endl; }};class Engine {public:Engine() { cout << "Engine contructor" << endl; }~Engine() { cout << "Engine destructor" << endl; }};7class CCar {private:Engine engine;Tyre tyre;public:Car( ) { cout << “Car contructor” << endl; }~Car() { cout << "Car destructor" << endl; }};int main(){Car car;return 0;}


The output is:
Engine contructor
Tyre contructor
Car contructor
Car destructor
Tyre destructor
Engine destructor


According to the specification, the call sequence is different from the compiler sequence, so the output is also different.


[Refer to Tips]
#include
 
  using namespace std;class Date{ public:Date( ){ cout<<"This is Date"<
 

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.