The C++ expert & D language creator Walter Bright says that:
The slicing problem is serious because it can result in memory corruption, and it is very difficult to guarantee a program does not suffer from it. To design it out of the language, classes that support inheritance should be accessible by reference only (not by value). The D programming language has this property.
It would be better if someone explain it by giving an C++ example where object slicing problem causes memory corruption? And how this problem is solved by D language?
Consider
class Account
{
char *name = new char[16];
public: virtual ~Account() { delete[] name; }
public: virtual void sayHello() { std::cout << "Hello Base\n"; }
};
class BankAccount : public Account
{
private: char *bankName = new char[16];
public: virtual ~BankAccount() override { delete[] bankName; }
public: virtual void sayHello() override { std::cout << "Hello Derived\n"; }
};
int main()
{
BankAccount d;
Account a1 = d; // slicing
Account& a2 = d; // no slicing
a1.sayHello(); // Hello Base
a2.sayHello(); // Hello Derived
}
Here a1
will leak bankName
when Account::~Account
, instead of BankAccount::~BankAccount
, runs because it has no way to invoke a polymorphic behavior. As why it is so specifically, it has been greatly explained here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With