ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
struct Base {
Base() { cout << "Base "; }
Base(int x) { cout << "Base(" << x << ") "; }
};
struct Derived : Base {
Derived() : Base(5) { cout << "Derived "; }
Derived(int x) { cout << "Derived(" << x << ") "; }
};
int main() {
Derived d1;
Derived d2(9);
}- A. Base(5) Derived Base Derived(9)
- B. Base Derived Base(9) Derived
- C. Base(5) Derived Derived(9) Base
- D. Base(5) Derived(9) Base Derived
Correct answer: A. Base(5) Derived Base Derived(9)
Derived() explicitly calls Base(5) in its initializer list, printing Base(5), then its own body prints Derived. Derived(int x) has no explicit base-constructor call, so the compiler implicitly inserts a call to Base's default constructor, Base(), printing Base, before Derived(x)'s own body prints Derived(9).
More OOP with C++ and Java questions
- What is printed? java class Node<T> { T value; Node<T> next; Node(T v) { value = v; } } public class Main { static <T> int length(Node<T>…
- What is printed? cpp struct Shape { virtual ~Shape() = default; }; struct Circle : Shape {}; struct Square : Shape {}; int main() { Shape…
- What is printed? java class Base { void process() { System.out.print("Base.process "); validate(); } protected void validate() {…
- What is printed? java class Base { public String toString() { return "Base[" + describe() + "]"; } protected String describe() { return…
- What is printed? cpp struct A { A() { cout << "A"; } }; struct B { B() { cout << "B"; } }; struct C : A, B { C() { cout << "C"; } }; int…
- What is printed? cpp struct Animal { virtual std::string sound() const { return "..."; } }; struct Dog : Animal { std::string sound()…