ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
struct Base {
Base() { cout << "Base "; }
Base(const Base&) { cout << "BaseCopy "; }
};
struct Derived : Base {
Derived() { cout << "Derived "; }
Derived(const Derived &other) : Base(other) { cout << "DerivedCopy "; }
};
int main() {
Derived d1;
Derived d2 = d1;
}- A. Base Derived BaseCopy DerivedCopy
- B. Base Derived Base DerivedCopy
- C. Base Derived BaseCopy Derived
- D. Base Derived DerivedCopy BaseCopy
Correct answer: A. Base Derived BaseCopy DerivedCopy
d1's construction runs Base() then Derived() (Base Derived). d2's copy-construction explicitly passes other to Base's copy constructor (Base(other) in the initializer list), running BaseCopy, and then Derived's own copy-constructor body runs, printing DerivedCopy.
More OOP with C++ and Java questions
- 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 << " "; } }…
- What is printed? cpp struct Animal { void speak() { std::cout << "Animal"; } }; struct Dog : Animal { void speak() { std::cout << "Dog"; }…
- What is wrong with this generic class? java class Factory<T> { T create() { return new T(); } }
- What is printed? java class A { static int x = init("x", 1); static { System.out.print("sA "); } static int y = init("y", 2); static int…
- What is printed? cpp struct Base { virtual void f() { std::cout << "Base "; } }; struct Mid : Base { }; struct Derived : Mid { void f()…