ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
class Base {
public:
    Base() { cout << "Base() "; }
    Base(int x) : Base() { cout << "Base(int) "; }
};
int main() { Base b(5); }
  1. A. Base(int)
  2. B. Base() Base(int)
  3. C. Compile-time error: a constructor cannot delegate to another constructor of the same class
  4. D. Base(int) Base()

Correct answer: B. Base() Base(int)

Base(int) : Base() is a delegating constructor (C++11): it first fully runs Base()'s body (printing Base()), and only afterward does Base(int)'s own body run (printing Base(int)). Delegating constructors must be the ONLY thing in the initializer list, which is satisfied here.

More OOP with C++ and Java questions

Exams that ask this topic