c z
c z

Reputation: 8977

C++ - Change the type of an object

In brief:

Is it possible to change the type of an object once established?

What I've tried:

For instance given the design: (edit: To clarify, this is a simplified example of a strategy design pattern, it isn't important what ChangeData does, only that 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 _interface allows us to change the operations upon the class, however this necessitates creating wrapper methods (DoChangeData) and always passing the this pointer as an argument, which is ugly.

A better solution I would prefer is:

struct MyClass abstract
{
    int _data;

    virtual void ChangeData() = 0;
};

But here once the concrete class is established, unlike _interface, it cannot be changed. It seems like this should be possible providing the different derived classes don't add any new fields. Is there any way to implement the ChangeClass function below?

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

Note I am talking about virtual classes, and reinterpret_cast only works with non-virtual objects. Copy constructors require the overhead of moving existing memory, which I would also rather avoid.

Upvotes: 4

Views: 985

Answers (2)

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32732

You could declare function pointers in MyClass and change them to change the type. Or create your own vtable with a (const pointer) to an array of function pointers, and just change this pointer to change the type.

Upvotes: 0

Matias SM
Matias SM

Reputation: 364

This looks like the kind of question that can be better answered if you explain the actual problem rather than how to implement your solution.

It is not clear to me what DoChangeData should do and why it requires a reference to MyClass. The problem statement is not clear enough to get an answer, and the title (as stated) would get a no as an answer (in C++ you can not change types, is a strongly typed language), but I understand is not what you are asking.

Please clarify the question to be able to get a satisfying answer.

BTW, you may want to pay a look at the Visitor design pattern and/or the Strategy design pattern.

Upvotes: 1

Related Questions