What is object slicing in C++ and how to avoid it?
Hello! I recently started learning C++ and encountered a problem that I can't understand. I have a base class `Animal` and a derived class `Dog` that adds a `breed` field. I wrote a function that takes `Animal` by value. When I pass a `Dog` object to it, the compiler doesn't give an error, but in the function I lose the breed data (the `breed` field). Here's my code:
```cpp
#include
#include
class Animal {
public:
Animal(const std::string& name) : name_(name) {}
virtual void speak() const { std::cout << "Animal sound\n"; }
std::string getName() const { return name_; }
private:
std::string name_;
};
class Dog : public Animal {
public:
Dog(const std::string& name, const std::string& breed)
: Animal(name), bre
No answers yet.
Log in to leave an answer
Blogs