Little features: Add empty_struct, object_slicing

This commit is contained in:
Alex Hirsch 2021-01-21 16:06:32 +01:00
parent 585965ec7c
commit 5062391b66
2 changed files with 64 additions and 0 deletions

View File

@ -0,0 +1,10 @@
#include <iostream>
// Emptry structs are valid in C++, not so in C.
struct Empty {
};
int main()
{
std::cout << sizeof(Empty) << "\n";
}

View File

@ -0,0 +1,54 @@
#include <iostream>
#include <memory>
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 = &rect;
{
const auto area = shape_ptr->area();
std::cout << "Area of shape_ptr: " << area << "\n";
}
std::shared_ptr<Shape> shape_sptr = std::make_shared<Rect>(3.0f, 4.0f);
{
const auto area = shape_sptr->area();
std::cout << "Area of shape_sptr: " << area << "\n";
}
}