ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
struct Base {
Base() { cout << "Base() "; }
Base(int x) { cout << "Base(int) "; }
};
struct Derived : Base {
Derived() { cout << "Derived() "; }
};
int main() { Derived d; }- A. Base(int) Derived()
- B. Base() Derived()
- C. Derived() Base()
- D. Compile-time error: Derived() must explicitly choose which Base constructor to call
Correct answer: B. Base() Derived()
Derived()'s member-initializer list is empty, so the compiler implicitly inserts a call to Base's default constructor, Base(). It runs first (printing Base()), and then Derived's own body runs, printing Derived(). Base(int) is simply never used.
More OOP with C++ and Java questions
- What is printed? java class Resource { Resource() { System.out.print("open "); throw new RuntimeException("ctor failed"); } void close() {…
- What is printed? cpp struct Base { virtual ~Base() { cout << "~Base "; } }; struct Mid : Base { ~Mid() { cout << "~Mid "; } }; struct Leaf…
- What is printed? java class Animal { Animal() { System.out.print(category() + " "); } String category() { return "Animal"; } } class Bird…
- What is printed? cpp struct Base { Base() { cout << "Base "; } Base(const Base&) { cout << "BaseCopy "; } }; struct Derived : Base {…
- What is printed? cpp int f() { std::cout << "f "; return 1; } int g() { std::cout << "g "; return 2; } int a = f(); int b = g(); int…
- What is printed? cpp struct X { int id; X(int i) : id(i) { std::cout << "X" << id << " "; } ~X() { std::cout << "~X" << id << " "; } }…