/* No inheritance */ #include class Rectangle { protected: int width; int height; public: Rectangle() : width(0), height(0) {} Rectangle(int w, int h) : width(w), height(h) {} int GetWidth() const { return width; } int GetHeight() const { return height; } int SetWidth(int w) { return (width = w); } int SetHeight(int h) { return (height = h); } }; class Square { protected: int side; public: Square(): side(0) {} Square(int s) : side(s) {} int GetSide() const { return side; } int SetSide(int s) { return (side = s); } operator Rectangle() const { return Rectangle(side, side); } }; void alterRectangle(Rectangle& rect) { rect.SetWidth(8); rect.SetWidth(10); } void dumpRectangle(const Rectangle& rect) { printf("%d x %d", rect.GetWidth(), rect.GetHeight()); } int main() { Square sq(7); alterRectangle(sq); // illegal (temporary can't be used as a reference) dumpRectangle(sq); // legal (implicit cast) return 0; } /* "const-inheritance" concept */ #include class Rectangle { protected: int width; int height; public: Rectangle() : width(0), height(0) {} Rectangle(int w, int h) : width(w), height(h) {} int GetWidth() const { return width; } int GetHeight() const { return height; } int SetWidth(int w) { return (width = w); } int SetHeight(int h) { return (height = h); } }; class Square : public const Rectangle { public: Square() : Rectangle() {} Square(int s) : Rectangle(s, s) {} int GetSide() const { return width; } int SetSide(int s) { return (width = height = s); } }; void alterRectangle(Rectangle& rect) { rect.SetWidth(8); rect.SetWidth(10); } void dumpRectangle(const Rectangle& rect) { printf("%d x %d", rect.GetWidth(), rect.GetHeight()); } int main() { Square sq(7); alterRectangle(sq); // illegal (argument isn't const) dumpRectangle(sq); // legal (Square inherits from Rectangle) return 0; }