r/cpp • u/NoSpite4410 • Sep 28 '26
Delegating Constructors
Delegating constructors allow the default constructor of a class to call the parameterized constructor by default.
This is somewhat unintuitive, but has a lot of applications in frameworks that generate components dynamically down inside their operation, but cannot take the arguments at that managerial level.
class SpecialWindow : public Gtk::Window {
public:
// 1. Parameterized Constructor
SpecialWindow(std::string inst_name, int inst_val)
: name(inst_name), val(inst_val) { // ... }
// default /w delegating constructor
SpecialWindow() : SpecialWindow("item 1", 100)
{ //... }
};
int main() {
auto app = Gtk::Application::create("org.gtkmm.examples.base");
return app->make_window_and_run<SpecialWindow>(argc, argv);
}I guess "everybody knew" that already, but I didn't.
0
Upvotes
View all comments
Show parent comment
1
u/alfps Oct 02 '26
Destructors are called for all so far successfully constructed sub-objects.
There is no difference with delegating constructors.
Pre C++11 one achieved the delegation effect manually by using a dummy base class to hold the state, with "delegation" to the base class.