C ++ - changing the type of an object

In short:

Can I change the type of an object after installing it?

What I tried:

For example, given the design: (edit: To clarify, this is a simplified example of a strategy design template, it doesn't matter what it does ChangeData, only what we can change, what it does by changing _interface)

struct MyClass
{
    int _data;
    MyInterface* _interface;

    void DoChangeData() { Interface->ChangeData(*this); }
};

MyClass x;
x._interface = new DerivedClass1();
x.DoChangeData(); // do something
x._interface = new DerivedClass2();
x.DoChangeData(); // do something else

Switching _interfaceallows us to change operations on the class, however this requires the creation of wrapper methods ( DoChangeData) and always passes a pointer thisas an argument, which is ugly.

The best solution I would prefer:

struct MyClass abstract
{
    int _data;

    virtual void ChangeData() = 0;
};

, , _interface, . , , . ChangeClass ?

DerivedClass1 x;
x.DoChangeData(); // do something
x.ChangeClass(DerivedClass2); // ???
x.DoChangeData(); // do something else

. , reinterpret_cast . , .

+4
2

, , , .

, DoChangeData MyClass. , , ( ) no ( ++ , ), , , .

, .

, / .

+1

MyClass . vtable ( const) , .

0

Source: https://habr.com/ru/post/1623683/


All Articles