Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can a factory method return 0 in case of an error?

I am studying a bit of code, which contains a factory method, if I am remembering my object orientation correctly.

The factory method and the related classes can be described by the following pseudo-C++.

The class Actor is the base class for the various implementations of concrete actions or operations, which in turn are implemented as derived classes.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The factory method createActor receives arguments which are read from an input script, hence prior to calling a constructor some error checking is being done.

I noticed, that in all cases when an error is detected, I find a return 0 statement.
This can obviously be done, since the code (not written by me) compiles and runs.

However, the factory method is supposed to return a pointer to an Actor-class.
Is in this case return 0 simply an obscure way to return NULL? Maybe I am overthinking this.

class Actor
{
  class ActorVariantA : Actor
  {
  }
  // all other ActorVariants are omitted for brevity

  Actor* createActor(arguments)
  {
    if (errorCondition)
      return 0
    if (conditionA)
      return new ActorVariantA(arguments)
  }
}

I found a somewhat related question, which in turn led me to Stroustrup himself.

So, the answer to my question would be: sort-of, but don’t do it.

>Solution :

yes, you are overthinking this. It should really be return nullptr, but in this case return 0 is equivalent.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading