2

So I have an object that can be constructed in a few ways. The constructors have signatures like, the one that loads an object from a file:

Object::Object( string filenameToLoadFrom ) ;

And how it behaves is pretty straightforward.

Object( "filename.dat" ) ; // loads object from filename

The constructor signature pretty much says what it does, although a static method Load might arguably be better:

static Object* Object::Load( string filenameToLoadFrom ) ;

(syntax above is slightly incorrect but you get the idea.)

Then we come into cases where what the constructor does isn't immediately obvious from the parameters. a name is needed to make it clear from the API what the constructor does.

The question is, is it a good idea to write static methods that return an instance of the object, just for the sake of being able to name the constructor?

bobobobo
  • 64,917
  • 62
  • 258
  • 363

2 Answers2

3

This is actually considered a common secondary benefit of the Factory Method Pattern. It is potentially useful in specific scenarios, especially for things where you have the same argument type providing very different meanings.

For example, it's not uncommon to have a class representing an "Angle" which can be constructed by a single floating point number which could represent degrees or radians. Constructors do not provide enough context (or a clean way) to implement this, where a "factory method" makes this very clear.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Interestingly, this is called the [Named Constructor idiom](http://www.parashift.com/c++-faq-lite/named-ctor-idiom.html). Named constructors also have the advantage of being able [to return NULL](http://stackoverflow.com/questions/2859062/can-a-constructor-return-a-null-value) in case of failure – bobobobo Jul 12 '12 at 20:55
0

I believe it's a good idea especially if you need more than one constructor that both take the same type of parameter(s). For example: static Object* loadFromFile( String fileName) and statc Object* loadFromResorce(String resourceName). You can even make the actual constructor private to enforce the use of the static constructors.

Rooster242
  • 911
  • 3
  • 10
  • 19