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"<