What is object slicing in C++ and how to avoid it?
Hi! I'm learning C++ and encountered a problem I can't understand. I have a base class `Shape` and a derived class `Circle`. When I pass a `Circle` object to a function that takes `Shape` by value, I lose the data and behavior specific to `Circle`. For example:
```cpp
#include
#include
class Shape {
public:
virtual void draw() const { std::cout << "Drawing Shape\n"; }
};
class Circle : public Shape {
public:
void draw() const override { std::cout << "Drawing Circle\n"; }
double radius = 5.0;
};
void printShape(Shape s) { // Takes by value
s.draw();
// std::cout << s.radius; // Error! radius is not in Shape
}
int main() {
Circle c;
printShape(c); // Outputs "Drawing Shape", not "Drawing Circle"
}
```