2.14.  Subobjects

[ fromfile: subobject.xml id: subobject ]

Example 2.22. src/subobject/subobject.h

[ . . . . ]
class Point {
 public:
    Point(int xx, int yy) : m_x(xx), m_y(yy){}
    ~Point() {
       cout << "point destroyed: ("
            << m_x << "," << m_y << ")" << endl;
    }
 private:
    int m_x, m_y;
};

class Square {
 public:
    Square(int ulx, int uly, int lrx, int lry)
    : m_UpperLeft(ulx, uly), m_LowerRight (lrx, lry)  1
    {}

    Square(const Point& ul, const Point& lr) :
    m_UpperLeft(ul), m_LowerRight(lr) {}              2
 private:
    Point m_UpperLeft, m_LowerRight;                  3
};

[ . . . . ]

1

Member initialization is required here because there is no default ctor.

2

Initialize members using the implicitly generated Point copy ctor.

3

Embedded subobjects.


Example 2.23. src/subobject/subobject.cpp

#include "subobject.h"

int main() {
    Square sq1(3,4,5,6);
    Point p1(2,3), p2(8, 9);
    Square sq2(p1, p2);
}

point destroyed: (8,9)
point destroyed: (2,3)
point destroyed: (8,9)
point destroyed: (2,3)
point destroyed: (5,6)
point destroyed: (3,4)


[20] Why not?

[21] Why can't you simply initialize m_x and m_y here?