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); }- A. Base(int)
- B. Base() Base(int)
- C. Compile-time error: a constructor cannot delegate to another constructor of the same class
- 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
- What is printed? java class Counter { int value; Counter(int v) { value = v; } Counter increment() { return new Counter(value + 1); }…
- What is printed? cpp struct Animal { virtual ~Animal() {} virtual void speak() const { cout << "..."; } }; struct Dog : Animal { void…
- What is printed? java class A { A() { System.out.print(id() + " "); } int id() { return 0; } } class B extends A { int val; B(int v) { val…
- What is printed? cpp struct Shape { virtual void draw() const { cout << "Shape "; } }; struct Group : Shape { std::vector<Shape> children…
- What is printed? cpp struct A { virtual void f() { cout << "A"; } }; struct B : A { void f() override { cout << "B"; } }; struct C : B {…
- Does this compile? java public class Main { public static void main(String[] args) { try { throw new RuntimeException("x"); } catch…