D
D
dalvreg2021-11-19 12:23:00
C++ / C#
dalvreg, 2021-11-19 12:23:00

How to change the type of an object within the object itself?

Is it possible to make it so that during the execution of the function of an instance of class A, under certain conditions, this object replaces itself with an instance of class B?
Accordingly, all variables referring to this object should already point to an instance of class B, and not A.

For example:

Class A
{
  public void Transform()
  {
    this = new B();
  }
}

just to make it work.

A and B are child classes of the same class C. They differ only in the implementation of some functions, if that matters.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
freeExec, 2021-11-19
@dalvreg

Because you're trying you can't.
Create a storage class that will give everyone A or B (in the form of class C) to everyone. And if necessary, replace them.

#
#, 2021-11-19
@mindtester

the confidence of colleagues is curious ... but it's a pity to waste time checking, alas))
it seems to me that this is possible in two, or at least in one case (but do you need them?)
- I'm not 100% sure without checking, but I suppose maybe if one of them is the heir Class A : Bor vice versa , Class B : Athis version just needs to be checked
- it’s definitely possible if object A
pps is still a spare - dynamic Abut the risks of gimor are the same / pps
but even if at least one of the options compiles, this is a minefield of errors and gimor. this is the only thing I can guarantee for sure
ps your question is rather in the context of one of the "eternal disputes" which is better? static ? or dynamic ? typing ?
perhaps your problem can be elegantly solved in another language. but only on the condition that it is not performance critical.. and yes, another condition is that the amount of code can be kept in one's head by one author and understand one's own logic for a long time (and your question is similar to a beginner's question, no offense ;))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question