ProgrammingVery hardProduct company OA
What is printed?
What is printed?
class Base {
public:
Base() { std::cout << "Base() "; }
virtual void show() { std::cout << "Base::show"; }
};
class Derived : public Base {
public:
Derived() { std::cout << "Derived() "; }
void show() override { std::cout << "Derived::show"; }
};
int main() {
Base *arr[2];
arr[0] = new Base();
arr[1] = new Derived();
for (auto *p : arr) p->show();
}- A. Base::showDerived::show
- B. Base() Derived() Base::showDerived::show
- C. Base::showBase::show
- D. Base() Base() Derived() Base::showDerived::show
Correct answer: D. Base() Base() Derived() Base::showDerived::show
Both objects are fully constructed before the loop runs. arr[0]=new Base() prints "Base() ". arr[1]=new Derived() runs Base's constructor then Derived's: "Base() Derived() ". Only then does the loop call show() virtually on each: the Base object prints Base::show, the Derived object prints Derived::show. Concatenated: Base() Base() Derived() Base::showDerived::show.
More OOP with C++ and Java questions
- What is printed? cpp class Complex { double re, im; public: Complex(double r, double i) : re(r), im(i) {} Complex operator+(const Complex&…
- What is printed? java interface Calculator { int calculate(int a, int b); } public class Main { public static void main(String[] args) {…
- What is printed? java class Matrix { int[][] data; Matrix(int[][] d) { data = d; } Matrix add(Matrix other) { int[][] r = new…
- What is printed? java class Vehicle { private int speed; protected void setSpeed(int s) { speed = s; } int getSpeed() { return speed; } }…
- What is printed? cpp class Stack { vector<int> data; public: void push(int x) { data.pushback(x); } int pop() { int top = data.back()…
- What is printed? java interface Repository<T> { void save(T item); T find(int id); } class UserRepository implements Repository<String> {…