Given I have a class with a constructor which looks as follows:
MClass(const char *t_source);
In fact there are a lot of places where t_source is obtained from a file, so I'm considering making another constructor which takes FILE pointer instead and put most of the boilerplate inside of it. At the same time existing constructor also has a lot of use by itself and contains logic which i don't want to repeat more than once in the code. I was thinking about delegating constructor but can't see any way how i can leverage this feature as i need more than one statement to extract data from a FILE instance (like allocating a char array and reading from the FILE and deleting afterward). So essentially I want to do something like this:
MClass(FILE *t_file) : MClass(MNameSpace::readFile(t_file)) {}
But with some preliminary and post-call actions. Any idea?
I find your case to be better solved by the named constructor idiom. Rather than trying to pigeonhole complexity into the limited space provided by the constructor context, I would simply add a new named function.
class MClass {
// ...
public:
static MClass fromFile(FILE *t_file);
};
MClass MClass::fromFile(FILE *t_file) {
// Preparation
MClass retVal(...);
// Post actions
return retVal;
}
Simple, easy to understand, and does what you want. It also conveys meaning very well when one sees
MClass obj = MClass::fromFile(...);
To boot, the named return value optimization (standardized) will avoid any extra copies from using a named function. The net result will be a single constructor invocation to initialize obj directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With