In the code below foo returns a type A object by value. Can I somehow convert this without handy interaction into a object of type B? (Note: class A includes all data/storage mebers, class B just introduces more methods)
class A{
/*data*/
A foo(...);
};
class B: public A
{
/*no-data*/
B doMagic(...);
};
/*usage*/
B bone;
B btwo = bone.foo(...) /*w\o cast*/
Thanks in advance!
You can’t, and that doesn’t make sense the way you wrote it; and you also got syntax errors.
You cannot convert actual base objects to derived objects, and you can’t usually sensibly go the other way, either. The usual thing you can do is convert pointers and references.
In your case, you would typically use a covariant return value on a virtual function:
You will need to think carefully about many, many details when pursuing this approach. It’s certainly feasible, but you have to get a lot of things right. You will probably need a couple of custom constructors to make
B::foo()do anything sensible.