You didn't mention which language you are using, but since the concept is pretty much the same across all OOP languages, I'll assume C# for the moment.
The only way you can do an implicit conversion like the one you sited in your example is if Invoice is a subclass of TempInvoice, like so:
public class Invoice : TemplInvoice { }
However, you can do an explicit conversion if the opposite is true (i.e. TempInvoice derives from Invoice), but only if the getInvoice
method is truely creating a TempInvoice object, or an object derived from TempInvoice. Otherwise, you will get an InvalidCastException
when you try to do the explicit conversion. Keep in mind that only platforms like Java or Microsoft.NET will throw a nice, clean exception for you to catch. Things can get much nastier from languages like C or C++, as they will allow you to do things like a blind cast without so much as warning (static_cast and dynamic_cast will fail to compile), which often results in either garbage data (best case), or an access violation (worst case) at random points farther down in the code.
If you absolutely need to have two objects, probably the best thing to do is to either derive one from the other, or break out the common methods into a seperate base class that both can inherit from. However, you should never blindly downcast a return value from a function call. If you have a case where you know a function will always return the same type, you should use that type directly, and avoid downcasting, anyway. It's safer and more efficient for the generated code. If you are using the factory pattern, you can build some form of RTTI into the base interface so that you aren't doing a (mostly) blind cast. A good example of this (albiet a bit complicated) is the QueryInterface method for COM objects, but you can do something as simple as adding an Invoice.Type property.