I have to cast the return pointer of GetType (maybe to CDog and CCat but that can't be done) so that there're no errors in main with the function call.I know I can change types of Dog and Cat to parent class, but I just wonder if I can cast the return type of the function.How can I do it (if it can be done)?
Thanks in advance :)
Dog = static_cast<CDog*>( CFactory::GetType(DogType) );
// .. or
Dog = dynamic_cast<CDog*>( CFactory::GetType(DogType) );
dynamic_cast will do a runtime check to make sure what you're trying to cast is really a CDog, and will give you a null pointer if it doesn't. static_cast will assume that the cast is okay (even if it isn't!). dynamic_cast has a little more overhead than static_cast, but is safer. A bad static_cast could have disasterous consequences that are hard to find and solve.
Right I did that already and it didn't work, but when I copied your code it worked!Obviously when I tried it I missed the "*" after CDog and wrote <CDog> without the *.Thanks Disch :)
One more thing - can I make CFactory a singleton so that when using GetType second time it produces an error?I did that with variables but what about functions?
One more thing - can I make CFactory a singleton so that when using GetType second time it produces an error?I did that with variables but what about functions?
I don't follow you.
You mean like:
1 2
Dog = CFactory::GetType (DogType);
Cat = CFactory::GetType (CatType); // you want a compiler error here?
If that's what you mean, then no there's no way to do that.
You can make CFactory a singleton, but that implies something else, and wouldn't have much meaning here because CFactory only has static members anyway.
Sorry I didn't write it clear but yes that's what I thought.Actually I wanted to ask if there could be a singleton class implementation with functions (not with variables as it's supposed to), however as I read what I've written it does sound confusing (I was too sleepy ;D ) !Yet you answered my question!Thanks Disch for all your attention :) I think that's it (for now...) :)