I have an abstract class called user, and 2 sub classes: RegisteredUser & VisitorUser. I have a need to convert a VisitorUser object to a RegisteredUser object - do I use casting to achieve this? If so, how?
You can't. You can view either as a User
but you cannot cast RegisteredUser
to VisitorUser
or vice versa, as they are different types.
You could make a conversion method, that returns a new instance of RegisteredUser
from an instance of VisitorUser
. However, I would rethink the abstraction so the status of the user becomes a part of the state of the object instead of a part of the type itself.
Short answer: You can't.
Long answer:
If you have base A and B and C are derived from A, you can not cast from B to C.
However, you can have a function defined in class B named toC()...
similarly, you could have a function in class C named toB()...
Yes, rethink your inheritance.
If you really really have to convert a VisitorUser to a RegisteredUser, a better way of doing it may be using an implicit or explicit conversion operator: Details from MSDN
That would allow you to define how one type converts to another, and you'll be able to use normal casting syntax to go from one to the other.