Is there a shortcut to take a base class and transform it into one of its derived classes inside of a program? For example:
Let’s say I have three classes, a base class and two derived classes:
class cColor {
};
class cBlue : public cColor {
};
class cRed : public cColor {
};
and then I create a Color class inside of my program:
int main(){
cColor unsaturated
return 0;
}
Is there someway to transform unsaturated from a cColor class to a cBlue or cRed class? Would a similar solution be to store unsaturated in a pointer, create a new cBlue or cRed class from the pointer and then delete unsaturated?
There is no way to change the type of an object after it was created (with the exception of construction and destruction, where the derived class object temporarily turns into a base class object). Since derived class objects can be larger than their base classes, there’s also no way this could ever work.
The workaround of creating a new derived object, resetting the pointer and then destroying the base object works if there’s no one else holding another pointer to the base class. If there’s any other pointer or reference to the original object, it will be dangling afterwards. But if you are in control of the only pointer/reference to the class (e.g. if you only access it through a singleton proxy object which never leaks a pointer or reference to the real object) then this method works.