diff --git a/topic/little_features/empty_struct.cpp b/topic/little_features/empty_struct.cpp new file mode 100644 index 0000000..dae28f6 --- /dev/null +++ b/topic/little_features/empty_struct.cpp @@ -0,0 +1,10 @@ +#include + +// Emptry structs are valid in C++, not so in C. +struct Empty { +}; + +int main() +{ + std::cout << sizeof(Empty) << "\n"; +} diff --git a/topic/little_features/object_slicing.cpp b/topic/little_features/object_slicing.cpp new file mode 100644 index 0000000..33649f6 --- /dev/null +++ b/topic/little_features/object_slicing.cpp @@ -0,0 +1,54 @@ +#include +#include + +struct Shape { + virtual float area() const + { + std::cout << "Shape::area\n"; + return 0; + } + + virtual ~Shape() {} +}; + +struct Rect : public Shape { + Rect(float width, float height) : width(width), height(height) {} + + float area() const override + { + std::cout << "Rect::area\n"; + return width * height; + } + + float width, height; +}; + +int main() +{ + std::cout << "size of Shape: " << sizeof(Shape) << "\n" + << "size of Rect: " << sizeof(Rect) << "\n"; + + Rect rect{2.0f, 3.0f}; + { + const auto area = rect.area(); + std::cout << "Area of rect: " << area << "\n"; + } + + Shape shape = rect; // rect gets sliced to fit into shape. + { + const auto area = shape.area(); + std::cout << "Area of shape: " << area << "\n"; + } + + Shape *shape_ptr = ▭ + { + const auto area = shape_ptr->area(); + std::cout << "Area of shape_ptr: " << area << "\n"; + } + + std::shared_ptr shape_sptr = std::make_shared(3.0f, 4.0f); + { + const auto area = shape_sptr->area(); + std::cout << "Area of shape_sptr: " << area << "\n"; + } +}