Elan Hickler
Elan Hickler

Reputation: 1139

C++ overload parenthesis operator to construct class/object after initialization?

Is it possible to be "DRY" (do not repeat yourself")? I would like to declare my class and essentially construct it later.

this code works:

// default constructor        
UserInput::UserInput() {}; 

// other constructor
UserInput::UserInput(string title, string section, string subsection) :
    title(title), section(section), subsection(subsection) {
    SPLIT();
}

// i want to be "DRY", is it possible?
// this is the same code as the "other constrcutor"
void UserInput::operator()(string title, string section, string subsection) {
    this->title = title;
    this->section = section;
    this->subsection = subsection;
    SPLIT();
}

this does not work, the class ends up with blank strings:

void UserInput::operator()(string title, string section, string subsection) {
    UserInput(title, section, subsection);
}

Upvotes: 0

Views: 245

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118292

void UserInput::operator()(string title, string section, string subsection) {
    *this = UserInput(title, section, subsection);
}

This is not terribly efficient, but if performance is not an issue for you, this will do the trick.

void UserInput::operator()(const string &title, const string &section, const string &subsection) {
    *this = UserInput(title, section, subsection);
}

This will be a little bit efficient. You should also make the same change to the real constructor's parameters, as well.

EDIT: here' an alternatve approach referenced in the comments. This is a bit more "standard-ish". It is quite common for constructors to invoke additional class methods to finish constructing object. This only works when class members have default constructors. As mentioned earlier, there's some duplicated effort here -- the class members get default-constructed first, only to be fully constructed again. But, it does tend to eliminate code duplication, and is a bit cleaner when performance or efficiency isn't at the premium.

UserInput::UserInput(const string &title, const string &section, const string &subsection)
{
    operator()(title, section, subsection);
}

void UserInput::operator()(const string &title, const string &section, const string &subsection) {
    this->title = title;
    this->section = section;
    this->subsection = subsection;
    SPLIT();
}

Upvotes: 1

Related Questions