Logo

Can I call a constructor from another constructor (do constructor chaining) in C++?

Yes. In C++11 and later, you can use delegating constructors to call one constructor from another within the same class. This feature allows you to factor out common initialization logic into a single “master” constructor, reducing code duplication.

1. How Delegating Constructors Work

You can invoke one constructor from another in the initializer list, like this:

class MyClass { public: // Constructor #1 delegates to Constructor #2 MyClass(int x) : MyClass(x, 0) { // Body of Constructor #1 (executes after Constructor #2 finishes) } // Constructor #2 does the "real" work MyClass(int x, int y) { // Initialization logic for (x, y) this->x_ = x; this->y_ = y; } private: int x_, y_; };

Key Points:

  1. The call to MyClass(x, 0) happens in the initializer list, not in the constructor body.
  2. Only one constructor can be called from another constructor. You cannot chain multiple constructors sequentially.
  3. You can still include additional initialization steps in the delegating constructor’s body, but those statements run after the delegated constructor finishes.

2. Why Use Delegating Constructors?

  1. Avoid Code Duplication
    If multiple constructors share a large portion of initialization logic, you can place that common code in one “master” constructor. The others delegate to it, making the code DRY (“don’t repeat yourself”).

  2. Readability and Maintenance
    Grouping all initialization logic in one place can make your class easier to maintain, especially if you need to make updates later.

  3. Cleaner Default Constructors
    You might have a default constructor delegating to a parameterized one for standard initial values:

    class Foo { public: Foo() : Foo(42) {} // Delegating to parameterized constructor Foo(int val) : value_(val) {} private: int value_; };

3. Common Pitfalls

  1. Cyclic Delegation
    You cannot have Constructor A delegate to Constructor B, which in turn delegates back to A. This will result in a compile-time error because it creates an infinite loop of constructor calls.

  2. Only One Call Allowed
    You can’t call two different constructors from the same delegating constructor. For example:

    // INVALID: You can't do this MyClass(int x) : MyClass(x, 0), MyClass(x, 10) { }

    You must choose exactly one constructor to delegate to.

  3. Order of Execution
    The delegated constructor runs first, initializing the object. Then, the delegating constructor’s body (if any) executes. Keep in mind that data members are fully initialized by the time you reach the delegating constructor’s body.

4. Example of a Delegating Constructor

#include <iostream> class Person { public: // Constructor #1: Delegating to the "master" constructor Person() : Person("Unknown", 0) { std::cout << "Default constructor called.\n"; } // Constructor #2: Delegating to the "master" constructor Person(const std::string& name) : Person(name, 0) { std::cout << "Constructor with name called.\n"; } // The "master" constructor Person(const std::string& name, int age) : name_(name), age_(age) { std::cout << "Master constructor called.\n"; } private: std::string name_; int age_; }; int main() { Person p1; // Calls Person() -> delegates to Person("Unknown", 0) Person p2("Alice"); // Calls Person(const std::string&) -> delegates to Person("Alice", 0) Person p3("Bob", 25); // Directly calls the "master" constructor return 0; }

Output (order may vary slightly by compiler):

Master constructor called.
Default constructor called.
Master constructor called.
Constructor with name called.
Master constructor called.

Why This Matters for Coding Interviews

  1. Demonstrates Modern C++ Knowledge
    Delegating constructors, introduced in C++11, show familiarity with new features and best practices.

  2. Code Organization
    Interviewers often look at how you handle repetitive initialization code. Using delegating constructors signals clean, maintainable design.

  3. Reduced Errors
    Minimizing copy-paste logic reduces the risk of bugs in large codebases—an important skill in real-world projects.

If you want to level up your C++ interview skills, here are a couple of resource suggestions from DesignGurus.io:

  1. Grokking the Coding Interview: Patterns for Coding Questions – Learn the recurring coding patterns that routinely appear in interviews.
  2. Grokking Data Structures & Algorithms for Coding Interviews – Build a strong foundation in algorithmic problem-solving.

You can also explore the DesignGurus YouTube channel for free system design and coding tutorials, or schedule a mock interview with an ex-FAANG engineer for personalized feedback.

Key Takeaway
Yes, you can perform constructor chaining in modern C++ by using delegating constructors. Simply call one constructor from another in the initializer list, ensuring you only delegate to one constructor, thus avoiding cyclical references or multiple calls. This can make your code more organized and easier to maintain.

CONTRIBUTOR
TechGrind