D
D
Daniil Demidko2016-03-12 12:47:00
C++ / C#
Daniil Demidko, 2016-03-12 12:47:00

Casting a derived class object to a base class?

Experimenting with OOP.
If you bring the derived class object to the base one, the fields declared in the derived class disappear? What if you use link casting?
For example:

class Base{};
class Exp: public Base
{
int i=0;
public:
           int Get() const {  return i; }
           void Set(const int &num) { i=num; }
};
std::vector<Base> MyStack;
Base &GetRef()
{           return *MyStack.begin();               }
int main(){
                Exp a;
                a.Set(4);
                MyStack.push_back(a);
                int res=((Exp&)GetRef()).Get(); // Не работает, мусор из стека
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stanislav Makarov, 2016-03-12
@Daniro_San

fields declared in a derived class disappear?

This is called object slicing . This phenomenon manifests itself in languages ​​where complex data types like classes and records a) can be inherited and add new fields when inherited; b) can be assigned by value. This leads to the fact that the fields of the descendant are cut off when assigned to a variable of the ancestor type. Such an assignment in itself is incorrect, because if you work with objects of derived classes through the interface of the base class, this implies polymorphic behavior and work through a reference / pointer, i.e. so that instead of the object itself, a link / pointer to it (i.e. its identity, "unique key") is copied, while the object itself remains untouched and lies in the same place where it lay.
When working through a REFERENCE to the base class (i.e.Base&) there will be no such problems, but the reference itself is not a variable (unlike a pointer) - it is just an additional NAME for some other variable or memory area. Therefore, you won't be able to store the reference in the vector - your code won't compile. In a vector, you will need to store pointers. For example, std::vector<Base*>.
Remember a simple rule - if your objects are supposed to work through the interface of the base class (ie polymorphic behavior), then in most cases you should work with them through a pointer (and, in most cases, allocate these objects on the heap). Including through smart pointers (unique_ptr, shared_ptr).
In other languages ​​(C#, D, for example) there is a fundamental separation between value types and reference types, and for all reference types work "by reference" is provided automatically. There is no such separation in C++, and you choose how to work with the type yourself when you use it (i.e. use it either by value or through a pointer).
PS Happy birthday!

L
LexArd, 2016-03-12
@LexArd

Find this book: www.ozon.ru/context/detail/id/1631049 everything is written there, as far as I remember.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question