ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
class Base {
public:
Base(int x) { cout << "Base(" << x << ") "; }
};
class Derived : public Base {
public:
Derived() : Base(42) { cout << "Derived() "; }
Derived(int y) : Base(y) { cout << "Derived(" << y << ") "; }
};
int main() {
Derived d1;
Derived d2(7);
}- A. Base(42) Derived() Base(7) Derived(7)
- B. Derived() Base(42) Derived(7) Base(7)
- C. Base(0) Derived() Base(0) Derived(7)
- D. Compilation error: Base has no default constructor
Correct answer: A. Base(42) Derived() Base(7) Derived(7)
Base has no default constructor, so every Derived constructor MUST explicitly initialise it in its member-init list, which both do (Base(42) and Base(y)). Base always runs first for each object: Base(42) then Derived() for d1; Base(7) then Derived(7) for d2.
More OOP with C++ and Java questions
- What is printed? java class Outer { static class Nested { void show() { System.out.print("Nested.show"); } } } // in main: Outer.Nested n…
- What is printed? java interface Shape { double area(); static Shape unitSquare() { return () -> 1.0; } } // in main: Shape s =…
- What is printed? java class Shape { protected String name = "Shape"; Shape() { System.out.print(name + " "); } } class Circle extends…
- What is printed? cpp class Account { double balance; public: explicit Account(double b) : balance(b) {} double get() const { return…
- What is printed? java class Base { protected Object clone2() { return new Base(); } } class Sub extends Base { @Override public Object…
- What is printed? java class Shape { double area() { return 0.0; } } class Rectangle extends Shape { double w, h; Rectangle(double w…