Reputation: 83
I would like to know if there is a way to program a class conversion in c++ I'am not talking about any form of type_casting, but a clone and convert of an instance to another one.
If I have this code :
class BaseClass
{
string baseData;
};
class DerivedClassB : public BaseClass
{
int intData;
};
class DerivedClassA : public BaseClass
{
float floatData;
};
lets say that I have an instance of DerivedClassA, and I would like to 'convert' that instance to DerivedClassB or even BaseClass i'm not concerned about the loss of the 'floatData', as long as the 'baseData' of the BaseClass is kept
can I achieve converssion from any type to any type ?
BaseClass -> DerivedClassA
DerivedClassA -> DerivedClassB
DerivedClassB -> BaseClass
How would I have to implement such functionnality ?
Thanks very much for the enlightenment.
Upvotes: 0
Views: 693
Reputation: 21576
Can I achieve conversion from any type to any type ?
Well, Yes, that's the purpose of reinterpret_cast
right?. But you'll most likely invoke Undefined Behavior if you break strict aliasing rules
How would I have to implement such functionnality ?
For your use case, you may simply provide a Converting Constructor.
//Forward declaration
class BaseClass;
class DerivedClassB;
class DerivedClassA;
class BaseClass
{
//Converting constructor: DerivedClassB -> BaseClass
BaseClass(const DerivedClassB&);
BaseClass() = default;
string baseData;
};
class DerivedClassB : public BaseClass
{
//Converting constructor: DerivedClassA -> DerivedClassB
DerivedClassB(const DerivedClassA&);
DerivedClassB() = default;
int intData;
};
class DerivedClassA : public BaseClass
{
//Converting constructor: BaseClass -> DerivedClassA
DerivedClassA(const BaseClass&);
DerivedClassA() = default;
float floatData;
};
// --------------------------
//Implement them out of class
Upvotes: 1