Помогите разобраться с буржуйским код стайлом
От: Аноним  
Дата: 07.06.08 12:25
Оценка:

The "slicing" of objects shall be avoided.

Explanation:

When an instance of a derived class is assigned or copied to an instance of its base class, any properties and methods of the derived class are dropped or "sliced". The remaining members of object may be in a state that, while consistent for the child, is no longer consistent with the parent. This may lead to unpredictable behavior or incorrect logic operations.

Example:

Improper Usage

class Base {
public:
       virtual void Print() { cout << "Base" << endl; };
};

class Derived : public Base {
public:
       void Print() { cout << "Derived" << endl; };
};

void PrintObject(Base obj)
{
     obj.Print();
}

...
    Derived obj;
    
    PrintObject(obj); //object slicing!!!
...


Proper Usage
class Base {
public:
       virtual void Print() { cout << "Base" << endl; };
};

class Derived : public Base {
public:
       void Print() { cout << "Derived" << endl; };
};

void PrintObject(Base& obj)
{
     obj.Print();
}

...
    Derived obj;

    PrintObject(obj); //now all is ok, reference is argument
...

Непонятно что за "slicing" properties мне казалось такого не может быть в C++. И как здесь спасет ссылка на базовый класс.
Добавлено форматирование, убран двойной интервал — Кодт
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.