Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How object slicing can result in memory corruption?

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?

like image 719
Destructor Avatar asked Jan 07 '23 15:01

Destructor


1 Answers

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.

like image 199
edmz Avatar answered Jan 16 '23 16:01

edmz